简体   繁体   English

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

[英]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 . variable是构造函数Example::Example的本地变量。 This means that it cannot be used after it goes out of scope at the closing brace } of the same ctor.这意味着它在同一 ctor 的右大括号}处超出范围后无法使用。

You can instead make variable to be a data member as shown below:您可以改为使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
};

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从外部“ C”函数访问类变量? - How do I access a class variable from an extern “C” function? 您如何在类的成员函数中调用复制构造函数? - How do you call the copy constructor within a member function of a class? 如何从类中的另一个函数访问变量 - How to access the variable from another function in a class 如何从C ++中的main函数访问类中的私有构造函数? - How do I access a private constructor in a class from the main function in C++? constructor.function(constructor)如何将相同类的对象传递给函数? - constructor.function(constructor) How do you pass an object of the same class to a function? 如何从模板化类中的变量返回向量迭代器? - How do you return a vector iterator from a variable in a templated class? 您如何将结构作为 class 中的私有成员并为其创建参数化构造函数/设置器 function? - How do you have a struct as a private member in a class and creating a parameterized constructor/setter function for it? 如何从派生类中调用在派生类中重载的模板类函数? - c++ How do you call a template class function that is overloaded in the derived class, from the derived class? 如何从另一个类参数访问类构造函数参数 - How to access a class constructor parameter from the another class parameter 如何从派生类访问引用成员变量? - How do I access reference member variable from derived class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM