在另一个函数/构造函数 [C++] 中初始化后使变量只读

Make variable read-only after initialization in another function/constructor [C++]

本文关键字:初始化 只读 变量 C++ 函数 另一个 构造函数      更新时间:2023-10-16

我在 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数据成员是不寻常的事情。首先,它们使您的类不可分配(如果您依赖于编译器生成的赋值运算符)。只需将成员设为私有,不要让界面提供更改它的方法。