如何在c++类的构造中设置const成员变量
How to set a const member variable in a C++ class on construction?
这个问题可能与这些问题有相当多的重叠:
如何初始化类中的const成员变量
c++ 11中的Const成员变量
对象构造后初始化const成员变量
我想做的是像这样-
class myRectangle {
private:
const int length; //const mainly for "read-only" like
const int breadth; //protection
public:
myRectangle(int init_length, int init_breadth);
int calcArea(void);
void turn90Degrees(void);
/* and so on*/
}
其中长度和宽度都是只读的,防止在构建后更改。
当然,我的编译器不允许我在构造函数中设置它们,因为它们实际上是const…
我确实想出了一个变通办法,让它们保持不变,只实现getter方法,这样它们就不能被有效地改变,但我觉得我在这里错过了一个明显的解决方案。
我也觉得我在某种程度上误解了const的使用。那么,它"已经"是一个编译时契约,从那里开始不改变数据吗?因为在我的理解中,知道常量的大小在程序执行中占用的信息还不够吗?
顺便说一下,使常数静态的解决方案不适合我,因为我生成的每个矩形都应该有不同的大小。
谢谢你的回答和澄清!
解决方案:初始化列表/委托构造函数
MSDN来自Jason R的解决方案条目
在构造函数中使用初始化列表
class myRectangle {
private:
const int length; //const mainly for "read-only" like
const int breadth; //protection
public:
myRectangle(int init_length, int init_breadth) :
length(init_length), breadth(init_breadth)
{
// rest of constructor body can go here; `length` and `breadth`
// are already initialized by the time you get here
}
int calcArea(void);
void turn90Degrees(void);
};
相关文章:
- 在类 (C++) 之外设置 const int 成员变量
- 当设置为 const 变量时使用 nullptr
- PIMPL类的设置应该是const成员函数
- 如何使用设置运算符返回非 const 对象>
- 为什么设置const变量(将以相同的值存储)会导致不同的结果
- 如何使用const成员变量设置数组大小
- const_cast为函数const设置规则并破坏规则
- 尝试在类中设置对 const 引用成员的引用
- 为什么在设置类成员时会自动从 const 转换为 non-const 并发生?
- 如何在 const 方法上设置EXPECT_CALL
- 如何在C++中将 const int 设置为最大值
- 从子类设置const成员值
- 构造函数"const variables"设置的用于表示C++数组的边界?
- 定义需要在运行时设置的const静态
- C++ 映射/设置迭代器不可取消引用 --- map<const char *,字符串>
- 为某些函数设置类的一些私有成员为const
- 未将此指针设置为const的构造函数会导致未检测到的问题
- 为什么设置const char*会出现分割错误?
- 如何在c++类的构造中设置const成员变量
- 在c++中,将别名设置为const