【问题标题】:Why do we need to initialize the parameters beforehand in a parameterized constructor?为什么我们需要在参数化构造函数中预先初始化参数?
【发布时间】:2020-12-29 06:40:35
【问题描述】:

我声明一个类 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);
    };
    

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

    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;
    }

【问题讨论】:

  • 您似乎找到了答案。 comp c3; 仅在存在可以不带参数调用的构造函数时才有效。
  • 对。你写了comp c3;。这将调用不带参数的构造函数。但是没有没有参数的构造函数。所以它向你抱怨并说没有没有参数的构造函数。

标签: c++ oop parameters constructor default-constructor


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 2014-12-26
    • 1970-01-01
    • 2015-03-09
    • 2016-01-27
    • 1970-01-01
    相关资源
    最近更新 更多