Initializing a const member variable after object construction

匿名 (未验证) 提交于 2019-12-03 01:33:01

问题:

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.

回答1:

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){/*...*/} };

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; }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!