构造函数初始化列表不遵循顺序
Constructor initializer list doesn't follow order
我有以下代码:
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;
我希望输出是:“基本构造函数,测试:50”,但事实并非如此,因为 Base
构造函数在 variable
初始化之前被调用,那里没有错误也没有警告,它只是编译。
有什么方法可以让 Base
构造函数在之后被调用?或者这通常是糟糕的设计?
我试图通过将它们放入构造函数中来摆脱所有 init 方法及其调用,这种行为阻止我这样做。
Is there any way i can make Base constructor get called after?
没有。对象的构造函数必须在任何命名成员变量之前构造其基础 类。
I'm trying to get rid of all the init methods and their calls by putting them into constructor instead
这是一项值得的努力!
我假设您的 真实代码 variable
比 int
更复杂。因为如果它是一个整数,你可以简单地调用 Base(50)
.
您可以使用 delagating constructors 在任何构造函数开始初始化之前准备变量。
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;
};
我有以下代码:
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;
我希望输出是:“基本构造函数,测试:50”,但事实并非如此,因为 Base
构造函数在 variable
初始化之前被调用,那里没有错误也没有警告,它只是编译。
有什么方法可以让 Base
构造函数在之后被调用?或者这通常是糟糕的设计?
我试图通过将它们放入构造函数中来摆脱所有 init 方法及其调用,这种行为阻止我这样做。
Is there any way i can make Base constructor get called after?
没有。对象的构造函数必须在任何命名成员变量之前构造其基础 类。
I'm trying to get rid of all the init methods and their calls by putting them into constructor instead
这是一项值得的努力!
我假设您的 真实代码 variable
比 int
更复杂。因为如果它是一个整数,你可以简单地调用 Base(50)
.
您可以使用 delagating constructors 在任何构造函数开始初始化之前准备变量。
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;
};