2013-08-18 91 views
3

1.除了連接之外,還有什麼使用靜態結構?靜態結構 - 定義,對象,成員

static struct test //THIS ONE 
{ 
    int a; 
}; 

2.什麼是使用像這樣的靜態?當我創建這一點,並儘量使用靜態成員(通過結構對象)顯示「未定義的參考`測試::一'」

struct test 
{ 
    static int a; //THIS ONE 
}; 

3.什麼是使用創建一個靜態結構對象的?

struct test{ 
    int a; 
}; 

int main() 
{ 
    static test inst; //THIS ONE 
    return 0; 
} 
+2

沒有這樣的東西在C語言的靜態結構或類++。 – juanchopanza

+0

@juanchopanza我能夠聲明結構爲靜態的。我在想,如果我使用靜態結構,我將無法在外部文件或其他翻譯單元中引用它。這不是這樣嗎? – Kaushik

+0

@Kaushik:不是標準的C++,你不能。 [GCC拒絕第一個例子](http://ideone.com/nETZsE)。 –

回答

5
  1. 只有聯動具體 - 它會讓你test結構具有內部鏈接(只在當前文件可見)。 編輯:這僅適用於函數和變量聲明 - 不適用於類型定義。

    //A.cpp 
    static int localVar = 0; 
    
    void foo(){ localVar = 1; /* Ok, it's in the same file */ } 
    
    //B.cpp 
    extern int localVar; 
    void bar(){ 
    /* 
        Undefined reference - linker can't see 
        localVar defined as static in other file. 
    */ 
        localVar = 2; 
    } 
    
  2. 這是一個靜態字段。如果您在struct static中聲明某個字段,它將成爲該結構的所有實例的共享數據成員。

    struct test 
    { 
        static int a; 
    }; 
    
    
    // Now, all your test::a variables will point to the same memory location. 
    // Because of that, we need to define it somewhere in order to reserve that 
    // memory space! 
    int test::a; 
    
    int foo() 
    { 
        test t1, t2; 
        t1.a = 5; 
        test::a = 6; 
        std::cout << t2.a << std::endl; // It will print 6. 
    } 
    
  3. 這是靜態局部變量。這不會存儲在調用堆棧上,而是存儲在全局區域中,因此對同一個函數的所有調用將共享相同的變量。

    void foo() 
        { 
         static int i = 0; 
         i++; 
         std::cout << i << std::endl; 
        } 
    
        int main() 
        { 
         foo(); // Prints 1 
         foo(); // Prints 2 
         foo(); // Prints 3 
         return 0; 
        } 
    
+0

第2點:如何訪問它的主要地方?它給我一個錯誤「未定義的引用test :: a'」。 – Kaushik

+0

我會添加例子。 –

+1

@Kaushik添加,看看第2部分的例子。 –