簡體   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