繁体   English   中英

如何从类函数访问类构造函数变量?

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM