[英]Why is wrong constructor being called in parent class?
当我创建一个继承另一个 class 的 object 时,我希望像在 java 中一样调用采用相同参数的构造函数。
class Shape {
public:
int width, height;
Shape(){
std::cout << "in def";
width = 0;
height = 0;
}
Shape(int x, int y){
std::cout << "in const param";
width = x;
height = y;
}
void toString(){
std::cout << "\nwidth = " << width << ", height = " << height;
}
};
class Rectangle : public Shape{
public:
Rectangle(int x, int y){
std::cout << height;
}
};
当我执行
Rectangle test(10, 19);
打印“in def”。 为什么会这样? 不应该调用采用 2 个整数的构造函数吗?
该语言表示默认调用没有 arguments 的基本 class 构造函数。 如果要调用任何其他特定的构造函数,则需要显式执行:
Rectangle(int x, int y) : Shape(x, y) {
// ^_________^ call base class constructor
// taking 2 arguments
std::cout << height;
}
In C++, what happens is when you inherit from a class, and an object of child class is created, it will always call the parent class and as for your case, what you need to do is use Initializer list , you have to also explicitly告诉我们在初始化矩形时,形状也将像这样初始化:
class Rectangle : public Shape{
public:
Rectangle(int x, int y): Shape(x,y){
std::cout << height;
}
};
在 C++ 中,基础 class 的对象是派生 class 的子对象,如果不涉及虚拟 Z5FED3411FAF832174EF1F040028。 所有的子对象,包括成员和基类都是首先创建的,按照声明的顺序。 基地 object 将是第一个。 这意味着,当您创建Rectangle
时, width
和height
将被默认初始化, Shape
将使用默认构造函数创建,然后是Rectangle
本身。
因此,如果您将 output 添加到Rectangle
的构造函数,您将看到两者。您对Rectangle(int x, int y)
的调用会导致默认初始化Shape
。 类类型的默认初始化会考虑默认构造函数(如果可用)。 如果没有提供构造函数,则由编译器定义。
作为任何子对象,基础 class 可以从派生 class 的构造函数中的初始化列表中初始化,这就是可以调用Shape
的另一个构造函数的方式,请参见下面的示例。 可以通过这种方式在同一个 class 内委托构造函数调用。
class Shape {
public:
int width, height;
Shape() : Shape (0,0) {
std::cout << "in default c-tor\n";
}
Shape(int x, int y) : width(x), height(y) {
std::cout << "in parametrized c-tor\n";
}
};
class Rectangle : public Shape{
public:
Rectangle() {}
Rectangle(int x, int y) : Shape(x,y)
{
std::cout << height;
}
};
Rectangle r;
Output:
in parametrized c-tor
in default c-tor
在这种特殊情况下几乎不需要委托,但通常允许跳过在多个构造函数中重复相同代码的需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.