我正在努力与类继承建设秩序.假设我有这两个类:
class A {
public:
const int CONSTANT_A;
A(const int constant) : CONSTANT_A(constant) {
}
void write() {
std::cout << CONSTANT_A;
}
};
class B : public A {
public:
const int CONSTANT_B = 3;
B() :A(CONSTANT_B) {
write();
}
};
Run Code Online (Sandbox Code Playgroud)
B创建新对象时,CONSTANT_A不是3,因为类继承构造函数的顺序如下:
有没有办法强制成员常量首先初始化?这是最干净的方法吗?
你的常量B::CONSTANT_B可以是static,因为它不依赖于构造函数参数.
static在构造类对象之前初始化s(除非它们static也是!).
struct B : A
{
static const int CONSTANT_B = 3;
B() : A(CONSTANT_B)
{
write();
}
};
Run Code Online (Sandbox Code Playgroud)
如果B::CONSTANT_B它本身从构造函数参数中获取其值,则可能必须在ctor-member-initialiser中将该参数命名为两次.就我的想象而言,没有任何简单的解决方法.
struct B : A
{
const int CONSTANT_B;
B(const int constant)
: A(constant)
, CONSTANT_B(constant)
{
write();
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
86 次 |
| 最近记录: |