如何在c++类的构造中设置const成员变量

How to set a const member variable in a C++ class on construction?

本文关键字:设置 const 成员 变量 c++      更新时间:2023-10-16

这个问题可能与这些问题有相当多的重叠:

如何初始化类中的const成员变量
c++ 11中的Const成员变量
对象构造后初始化const成员变量

然而,这些都不能回答我最初的问题。主要的区别在于,我不想用set值初始化,而是用构造函数参数初始化。

我想做的是像这样-

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