[英]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.