【问题标题】:Unable to initialize private const member [duplicate]无法初始化私有 const 成员 [重复]
【发布时间】:2015-10-14 11:47:25
【问题描述】:

我希望有一个与我的类相关联的int,它是在此类的用户实例化它时设置的。

class MyClass {
public:
  MyClass(int x);
private:
  const int x;
};

为了初始化这个常量,我尝试使用构造函数(Java 风格):

MyClass::MyClass(int x) {
  this->x = x;
}

但是,我的编译器不太喜欢这种方式,我得到以下信息:

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

C++ 中基于构造函数(如 Java)初始化实例化常量的方法是什么?

编辑:我看到标记为重复的问题;该线程没有提到您可以在初始化列表中使用构造函数的参数,因为它在所有示例中只使用数字文字。

【问题讨论】:

  • 使用initialiser list: MyClass::MyClass(int x) : x(x) {}
  • 顺便说一句,也将它用于非常量成员......
  • 使用初始化,而不是赋值。
  • 这不是问题的重复。另一个问题是关于在类的声明中初始化一个const int,而这是关于传递一个参数来初始化它。

标签: c++ constructor initialization constants


【解决方案1】:

您可以在构造函数的函数签名中使用所谓的初始化列表:

MyClass::MyClass(int x) : x(x) {
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    相关资源
    最近更新 更多