我在 Ah 文件中有一个类:
class A {
...
public:
A();
...
private:
bool t = false;
...
}
在 A.cpp 文件中:
A::A() {
...
t = true; <- after this point, have t be const or readonly
...
}
这可能吗?还是我必须使用不同的值?
不幸的是,你不能这样做。
但是,您仍然可以做您想做的事情(您可以更改确切的机制以满足您的确切需求,因为您不太清楚):
class A {
...
public:
A();
...
private:
bool A::init_A_impl();
const bool t_;
...
};
bool A::init_A_impl()
{
bool t = false;
...
t = true; <- after this point, have t be const or readonly
...
return t;
}
A::A() : t_(init_A_impl())
{
}
成员的类内初始化在 C++11 中工作:
class A {
public:
A();
private:
const bool t = false;
};
在 C++11 之前,您将使用成员初始值设定项列表:
class A {
public:
A() : t(false) {}
private:
const bool t;
};
但是const
数据成员是不寻常的事情。一方面,它们使您的类不可赋值(如果您依赖编译器生成的赋值运算符)。只需将成员设为私有,不要让界面提供更改它的方法。