问题描述
我经常发现自己希望对象的成员变量可以是const,但是系统允许在构造后初始化该const变量。有一种机制可以让我做到这一点吗?
I often find myself wishing I could have an object's member variable be const, but that the system allowed initialization of that const variable after construction. Is there a mechanism that would allow me to do this?
为了澄清,下面是一个示例:
To clarify, here is an example:
class A
{
public:
A(){}
initialize(int x) { c = x; }
private:
const int c;
}
我希望能够做到这一点。我在构造时没有此信息,因此不能简单地将初始化移到构造函数的初始化列表中。
I want to be able to do something like that. I don't have this information at construction, so I can't simply move initialization to the initialization list of the constructor.
推荐答案
不,您不能在构造后初始化const成员。
No, you cannot initialize const member after contruction.
但是请不要忘记,您可以在初始化列表中调用静态函数,因此在大多数情况下,您可以从初始值设定项列表中初始化成员
Do not forget, however, that you can call static functions in initializer list, so in most of cases you can initialize memebers from initializer list
class A
{
public:
A(){}
initialize(int x):c(computeC(x)) {}
private:
const int c;
static int computeC(int){/*...*/}
};
您还可以为该成员定义特殊的getter并使用它来访问成员。
You can also define special getter for that member and use it to access member.
class A
{
public:
A(){}
initialize(int x) { c_internal = x; }
private:
const int& c() const { return c_internal; }
int c_internal;
}
这篇关于在对象构造后初始化const成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!