简体   繁体   中英

How do you access a class constructor variable from a class function?

I don't really know how to phrase it so here's an example

class Example() {
    public:
        Example() {
            int variable;
        }

        void Function() {
            // How do you modify variable from here?
        }
}

variable is local to the constructor Example::Example . This means that it cannot be used after it goes out of scope at the closing brace } of the same ctor.

You can instead make variable to be a data member as shown below:

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

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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