[英]How do you access a class constructor variable from a class function?
我真的不知道如何表达它所以这里是一个例子
class Example() {
public:
Example() {
int variable;
}
void Function() {
// How do you modify variable from here?
}
}
variable
是构造函数Example::Example
的本地变量。 这意味着它在同一 ctor 的右大括号}
处超出范围后无法使用。
您可以改为使variable
成为数据成员,如下所示:
//-----------v------------->removed () from here
class Example {
public:
//-----------------vvvvvvvv------->use member initializer list to initialize variable
Example(): variable(0) {
}
void Function() {
//use variable as you want
variable++;
}
private:
int variable; // variable is a data member now
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.