在另一个函数/构造函数 [C++] 中初始化后使变量只读
Make variable read-only after initialization in another function/constructor [C++]
我在 A.h 文件中有一个类:
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
数据成员是不寻常的事情。首先,它们使您的类不可分配(如果您依赖于编译器生成的赋值运算符)。只需将成员设为私有,不要让界面提供更改它的方法。
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 为什么在C++中首先初始化成员类
- 同时具有"聚合初始化"和"模板推导"
- 初始化具有非默认构造函数的std::数组项的更好方法
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 在C和C++中初始化结构中的数组
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 犰狳C++ - 从常量内存初始化只读矩阵而不复制
- 在另一个函数/构造函数 [C++] 中初始化后使变量只读