Kaz*_*azz 1 c++ constructor derived-class
我有以下代码:
class Base
{
public:
Base(int test) { std::cout << "Base constructor, test: " << test << std::endl; }
};
class Derived : public Base
{
private:
int variable;
public:
Derived() :
variable(50),
Base(variable)
{}
};
Derived derived;
Run Code Online (Sandbox Code Playgroud)
我希望输出将是:“基本构造函数,测试:50”,但事实并非如此,因为Base构造函数在variable初始化之前被调用,没有错误或警告,它只是编译。
有什么办法可以让Base构造函数在之后被调用吗?或者这通常是糟糕的设计?
我试图通过将它们放入构造函数中来摆脱所有 init 方法及其调用,这种行为阻止我这样做。
有什么办法可以让 Base 构造函数被调用?
不可以。对象的构造函数必须在任何命名成员变量之前构造其基类。
我试图通过将它们放入构造函数来摆脱所有 init 方法及其调用
这是值得的努力!
我会假设您的真实代码 variable比int. 因为如果它是一个 int,你可以简单地调用Base(50).
您可以使用延迟构造函数在任何构造函数开始初始化之前准备一个变量。
class Derived : public Base
{
public:
// Generate an important value FIRST, and then delegate
// construction to a new constructor.
Derived() : Derived( GenerateSomethingComplex() ) {}
private:
// Here, we can honor constructing Base before Derived
// while "some value" has been procured in advance.
Derived( SomethingComplex&& var) :
Base( var ),
variable( std::move(var) )
{}
SomethingComplex variable;
};
Run Code Online (Sandbox Code Playgroud)