首页 > 解决方案 > 为什么我们需要在参数化构造函数中预先初始化参数?

问题描述

我声明一个类 comp 用于添加复数,在 add() 函数错误中声明第三个 comp 对象时弹出错误:没有匹配函数调用 'comp::comp()'

下面给出的代码工作得很好

 class comp
    {
        float real;
        float img;
    
    public:
        comp()
        {
            real=img=0;
        }
    
        comp(float a,float b)
        {
            real=a;
            img=b;
        }
    
        void display()
        {
            cout<<real<<"+"<<img<<"i"<<endl;
        }
    
        friend comp add(comp, comp);
    };
    

在代码中,我已经注释了 Default 构造函数,这会产生一个错误

    class comp
    {
        float real;
        float img;
    
    public:
        /*comp()
        {
            real=img=0;
        }*/
    
        comp(float a,float b)
        {
            real=a;
            img=b;
        }
    
        void display()
        {
            cout<<real<<"+"<<img<<"i"<<endl;
        }
    
        friend comp add(comp, comp);
    };
    

在下面的代码中,现在我已经在参数化构造函数中初始化了参数,这也可以正常工作

    class comp
    {
        float real;
        float img;
    
    public:
    
        comp(float a=0,float b=0)
        {
            real=a;
            img=b;
        }
    
        void display()
        {
            cout<<real<<"+"<<img<<"i"<<endl;
        }
    
        friend comp add(comp, comp);
    };

我在下面粘贴 add() 函数的代码

    comp add(comp c1, comp c2)
    {
        comp c3;   //*The error pops up at this declaration*
        c3.real=c1.real+c2.real;
        c3.img=c1.img+c2.img;
        return c3;
    }

标签: c++oopparametersconstructordefault-constructor

解决方案


您不是在“初始化参数”,而是在声明一个具有参数默认值的函数。这使得可以在不显式传递任何内容的情况下调用函数,因此它可以不带参数调用。


推荐阅读