简体   繁体   English

C ++,默认构造函数

[英]C++ , Default constructor

When a constructor in a superclass receives arguments, it is no longer a default constructor, right? 当超类中的构造函数接收参数时,它不再是默认的构造函数,对吗? For example 例如

class a {
    public:
      int a;
      int b;
      a(int c, int d){
        cout<<"hello";
      };
} 

Now when I try to make a subclass, the program causes an error, it says "no default constructor is defined in the super class". 现在,当我尝试创建子类时,该程序会导致错误,并显示“在超类中未定义默认构造函数”。 How can I solve this problem? 我怎么解决这个问题? I know that if I remove the arguments, everything is going to be fine but I'm told not to do so in my C++ test. 我知道,如果删除参数,一切都会好起来的,但是在我的C ++测试中,我被告知不要这样做。 Please help me figure it out. 请帮我弄清楚。

If your base class isn't default-constructible, or if you don't want to use the base class's default constructor, then you simply have to tell the derived class how to construct the base subobject: 如果您的基类不是默认可构造的,或者您不想使用基类的默认构造函数,则只需告诉派生类如何构造基子对象:

struct b : a
{
    b(int n) : a(n, 2*n) { }
    //         ^^^^^^^^^ <--  base class initializer, calls desired constructor
};

You have to provide a constructor which takes no argument yourself. 您必须提供一个自己不带参数的构造函数。

a::a()
{

}

Once you provide any constructor for your class the compiler does not generate the implicit default constructor which takes no arguments. 为类提供任何构造函数后,编译器将不会生成不带参数的隐式默认构造函数。 So if your code then needs a no arguments constructor you will have to provide it yourself. 因此,如果您的代码随后需要一个无参数的构造函数,则您必须自己提供它。

You normally deal with this with an initializer list: 您通常使用初始化列表处理此问题:

#include <iostream>

class a { 
public:
    a(int c, int d) { std::cout << c << " " << d << "\n"; }
};

class b : public a { 
public:
    b() : a(1, 2) {}
};

int main() { 
    b x;
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM