如何在 C++ class 构造中设置 const 成员变量?
How to set a const member variable in a C++ class on construction?
好吧,这个问题可能与这些问题有相当多的重叠:
how to initialize const member variable in a class C++
Const Member Variables in C++11
Initializing a const member variable after object construction
然而,其中 none 个可以回答我原来的问题。主要区别在于我不想使用设置值进行初始化,而是使用构造函数参数进行初始化。
我想做的是这样的-
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 的使用。那么 "already" 是不是从那里开始不更改数据的编译时合同?因为在我的理解中,不知道常量在程序执行中占用的大小是否足够信息?
顺便说一句,使常量静态的解决方案不适合我,因为我生成的每个矩形都应该有不同的大小。
感谢您的回答和澄清!
解决方案:初始化器列表/委托构造函数
在构造函数中使用初始化列表。
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);
};
好吧,这个问题可能与这些问题有相当多的重叠:
how to initialize const member variable in a class C++
Const Member Variables in C++11
Initializing a const member variable after object construction
然而,其中 none 个可以回答我原来的问题。主要区别在于我不想使用设置值进行初始化,而是使用构造函数参数进行初始化。
我想做的是这样的-
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 的使用。那么 "already" 是不是从那里开始不更改数据的编译时合同?因为在我的理解中,不知道常量在程序执行中占用的大小是否足够信息?
顺便说一句,使常量静态的解决方案不适合我,因为我生成的每个矩形都应该有不同的大小。
感谢您的回答和澄清!
解决方案:初始化器列表/委托构造函数
在构造函数中使用初始化列表。
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);
};