无法初始化私有const成员 [英] Unable to initialize private const member
问题描述
我想与我的课程相关联的 int
在该类的用户实例化它时设置。
I want to have an int
associated with my class that is set when the user of this class instantiates it.
class MyClass {
public:
MyClass(int x);
private:
const int x;
};
要初始化此常量,我尝试使用构造器(Java样式):
To initialize this constant, I try to use the contructor (Java style):
MyClass::MyClass(int x) {
this->x = x;
}
但是,我的编译器不太喜欢这种方式,我得到了以下内容:
However, my compiler doesn't quite like it this way, and I get the following:
const.cxx: In constructor ‘MyClass::MyClass(int)’:
const.cxx:3:1: error: uninitialized const member in ‘const int’ [-fpermissive]
MyClass::MyClass(int x) {
^
In file included from const.cxx:1:0:
const.h:8:13: note: ‘const int MyClass::x’ should be initialized
const int x;
^
const.cxx:4:11: error: assignment of read-only member ‘MyClass::x’
this->x = x;
^
基于构造函数la初始化实例化常量的C ++方法是什么Java吗?
What is the C++ way to initialize an instantiated constant based on the constructor a la Java?
编辑:我看到这个问题被标记为重复;该线程未能提及您可以在初始化器列表中使用构造函数的参数,因为它仅在所有示例中使用数字文字。
I saw the question marked as duplicate; that thread failed to mention you could use the constructor's parameters in the initializer list, since it only use numeric literals in all the examples.
推荐答案
您可以在构造函数的函数签名中使用所谓的初始化列表:
You can use what's called an initializer list in the constructor's function signature:
MyClass::MyClass(int x) : x(x) {
}
这篇关于无法初始化私有const成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!