例如,这:
class shape {
private:
int height;
int width;
public:
shape(int h, int w) {
height = h;
width = w;
}
void display() {
std::cout << height << "\t" << width << std::endl;
}
};
class square : public shape {
public:
square(int d) {
shape(d, d);
}
};
我收到以下错误消息:
no default constructor exists for class "shape"
为什么会这样呢?我知道它想要基类的默认构造函数,我想知道为什么要这样,并且如果我将square
构造函数的语法更改为初始化列表,请参见square(int d): shape(d, d){}
。程序成功编译。有什么不同?
只需通过这样调用构造函数即可:
class square : public shape {
public:
square(int d): shape(d, d)
{
}
};
重要的是在派生类的构造函数的主体之前调用构造函数。您还应该在构造函数主体之前初始化成员变量。
如果您不这样做,将完成所有对象的默认初始化,然后第二步完成分配。在您的示例中,您首先尝试使用父类的默认初始化,这是不可能的,因为您没有默认构造函数。
有关此主题的更多信息,请参见:http : //en.cppreference.com/w/cpp/language/initializer_list
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句