Mic*_*rst 0 c++ polymorphism constructor
可能重复:
C++超类构造函数调用规则
你如何将工作委托给超类的构造函数?例如
class Super {
public:
int x, y;
Super() {x = y = 100;}
};
class Sub : public Super {
public:
float z;
Sub() {z = 2.5;}
};
Run Code Online (Sandbox Code Playgroud)
我怎么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) { }
};
Run Code Online (Sandbox Code Playgroud)
您不需要显式调用基类的默认构造函数,它在运行派生类的构造函数之前自动调用.
另一方面,如果您希望使用参数构造基类(如果存在这样的构造函数),那么您 需要调用它:
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) { }
};
Run Code Online (Sandbox Code Playgroud)
此外,任何可以不带参数调用的构造函数也是默认构造函数.所以你可以这样做:
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
};
Run Code Online (Sandbox Code Playgroud)
并且只在不希望使用默认值初始化基本成员时才显式调用它.
希望有所帮助.