C/C++變數在嵌套域內可見

來源:互聯網
上載者:User

標籤:context   檔案   ++   end   include   名字空間   void   變數   程式   

C++程式中每個名字都必須指向唯一的一個實體(如對象、函數、類型或模板)。但是我們都知道,在一個程式中,經常出現相同的名字指向不同的實體。這個實現的機制就是編譯器根據上下文(Context)區分出名字的不同含義。而用來區分名字含義的一般上下文就是域(scope)。C++支援三種形式的域:局部域(local scope),名字空間域(namespace scope)和類域。

比如在一個cpp檔案裡,有一個全域變數,相對的裡面的函數就是這個全域域的嵌套域,這個全域變數在所有嵌套域可見。
又如class裡,又有一個class,那麼外層的變數在裡面的class也是可見的:

#include <iostream>using namespace std; class c1{public:    int a;    void foo();    class c2    {    public:        int a;        void foo();    } b;};void c1::foo(){    a = 1;}void c1::c2::foo(){    a = 2;} int main(){     class c1 f;    f.foo();    f.b.foo();    cout << f.a << endl;    cout << f.b.a << endl;    return 0;}

C/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.