c++ - 具有 Const 成员的构造函数的语法

标签 c++ constants

<分区>

我有一段时间没有写C++代码了,我的 friend 在作业上遇到了麻烦。我从未真正使用过 const,这让这成为一场噩梦,因为我无法找出构造函数的正确语法。假设我在 dvd.h 中有这个:

class DVD {
    const string title;
    int minutes;
    double price;

  public:
    DVD(const string t, int m, double p);
}

3个私有(private)成员变量,stringconst。构造函数还接受一个 const string

现在,在 dvd.cpp 中,我可以执行以下操作:

#include "dvd.h"

DVD::DVD(const string t, int m, double p) {
    const string title = t;
    minutes = m;
    price = p;
}

世界上一切都很好。但是,当我将 dvd.h 中的 minutes 修改为 const(这是他的教授构建文件的方式)时,我们在 DVD.h:

class DVD {
    const string title;
    const int minutes; // Here is the change
    double price;

  public:
    DVD(const string t, int m, double p);
}

所以,现在 minutesconst,我得到以下编译错误:

assignment of read-only member 'DVD::minutes'   dvd.cpp
uninitialized member 'DVD::minutes' with 'const' type 'const int' [-fpermissive]    dvd.cpp

我想这是有道理的,因为我正在尝试将一个值设置到一个const 变量中。因此,我尝试做与 dvd.cpp 中的 const string title 相同的事情,以解决错误:

DVD::DVD(const string t, int m, double p) {
    const string title = t;
    const int minutes = m; // Was 'minutes = m;'
    price = p;
}

并得到以下 (1) 个错误和 (1) 个警告:

uninitialized member 'DVD::minutes' with 'const' type 'const int' [-fpermissive]    dvd.cpp
unused variable 'minutes' [-Wunused-variable]   dvd.cpp

所以我想我正在努力弄清楚该死的语法是什么... titleminutes 应该是是 const,但是 DVD 的构造函数的参数列表只需要一个 const string。我不知道我错过了什么 - 自从我上次用 C++ 编码以来已经有一段时间了。

最佳答案

const string title = t;

声明一个局部变量。这个世界并不尽如人意:您还没有将成员变量设置为您想要的值。要初始化成员,请使用构造函数的初始化列表:

DVD::DVD(const string t, int m, double p) :
    title(t), minutes(m), price(p)
{}

您的版本尝试默认初始化每个成员(因为他们没有在初始化列表中提及),然后分配他们中的每一个。这不适用于无法默认初始化(例如引用或没有默认构造函数的类类型)或分配给(例如 const 成员)的成员。

关于c++ - 具有 Const 成员的构造函数的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21583825/

相关文章:

C++ 标准算法将一个表达式分成由最低优先级运算符分隔的 2 个表达式?

c++ - 允许这种派生到基础转换的理由是什么(当它似乎违反 IS-A 时)?

c - 指向 const 的指针是否与 __restrict 具有相同的效果?

c++ - 为什么我必须将映射值的类型从 & 更改为 (int*)&

initialization - 通用 Lisp : shorthand to initialize a hash table with many entries

c++ - 如何正确安装boost

c++ - Qt QLCDNumber QTimer 数字时钟刻度

c++ - 对于任何 C++ 函数,Mac 上的链接器错误,但 iOS 上没有

javascript - 在 JavaScript 中声明一个 const 有什么意义

c++ - 函数 const 返回类型 : invalid initialisation of reference of type