C++類的範圍和可見域

來源:互聯網
上載者:User

標籤:c++   類   全域變數   範圍   

        在類中定義的資料成員和函數成員的範圍是整個類,這些名稱只有在類中(包含類的定義部分和類外函數的實現部分)是可見的,在類外是不可見的。如果發生“屏蔽”的現象,類的成員的可見域小與範圍,但此時可藉助this指標或“類名::”的形式訪問類成員,這有些類似於使用“::“訪問全域變數。

      例子:

     extern int x=100;

     extern int z=100;

     class Example

   {

         int x;

         int y;

public :

              Example(int x,int y)

             {}

             void print(int x)

            {

                  cout<<"形參覆蓋了成員X變數和全域X變數"<<x<<end1;   //形參X覆蓋了全域變數和局部變數X

                  cout<<"成員X變數"<<(this->x)<<end1;

                  cout<<"成員X變數"<<Example::x<<end1;

                  cout<<"全域X變數"<<(::x)<<end1;                           //訪問全域變數X

                  cout<<"全域Z變數"<<z<<end1;                               //沒有形參對全域變數Z構成屏蔽,直接存取Z即可

            }

   }

 

int main()

(  

          Example  e;

          x.print(5);

          return 0;

         

)

 

輸出結果:

5

0

0

100

200

C++類的範圍和可見域

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.