可能重复:
C++ 超类构造函数调用规则
您如何将工作委托给超类的构造函数?例如
class Super {
public:
int x, y;
Super() {x = y = 100;}
};
class Sub : public Super {
public:
float z;
Sub() {z = 2.5;}
};
如何Sub::Sub()
调用Super::Super()
,以便我不必在两个构造函数中设置x
和?y
可能重复:
C++ 超类构造函数调用规则
您如何将工作委托给超类的构造函数?例如
class Super {
public:
int x, y;
Super() {x = y = 100;}
};
class Sub : public Super {
public:
float z;
Sub() {z = 2.5;}
};
如何Sub::Sub()
调用Super::Super()
,以便我不必在两个构造函数中设置x
和?y
使用构造函数的成员初始化列表:
class Super {
public:
int x, y;
Super() : x(100), y(100) // initialize x and y to 100
{
// that was assignment, not initialization
// x = y = 100;
}
};
class Sub : public Super {
public:
float z;
Sub() : z(2.5) { }
};
您不需要显式调用基类的默认构造函数,它会在派生类的构造函数运行之前自动调用。
另一方面,如果您希望使用参数构造基类(如果存在这样的构造函数),那么您 需要调用它:
class Super {
public:
int x, y;
explicit Super(int i) : x(i), y(i) // initialize x and y to i
{ }
};
class Sub : public Super {
public:
float z;
Sub() : Super(100), z(2.5) { }
};
此外,任何可以不带参数调用的构造函数也是默认构造函数。所以你可以这样做:
class Super {
public:
int x, y;
explicit Super(int i = 100) : x(i), y(i)
{ }
};
class Sub : public Super {
public:
float z;
Sub() : Super(42), z(2.5) { }
};
class AnotherSub : public {
public:
AnotherSub() { }
// this constructor could be even left out completely, the compiler generated
// one will do the right thing
};
并且仅当您不希望使用默认值初始化基成员时才显式调用它。
希望有帮助。
member initialize list
如果您愿意,可以调用基本构造函数,实际上 Super() 构造函数会被自动调用。
不要忘记将超级析构函数设为虚拟。
class Super {
public:
int x, y;
Super() : x(100),y(100) {}
virtual ~Super(){}
};
如果应该允许通过指向 Super 的指针进行删除,那么 Super 析构函数必须是公共的和虚拟的。