2016-01-17 83 views
0

我聲明一個函數結構內的對象,我想訪問該函數之外的所有對象(使它們成爲全局的)。這是我想要做的一個例子聲明一個函數內部的全局對象(C++)

  #include <iostream> 
      using namespace std; 

      struct exampleStruct 
      { 
       int ID; 
      }; 

      void makeExampleStruct() 
      { 
       exampleStruct exampleObj[30]; 

       for (int r=0;r<=30;r++) 
       { 
        exampleObj[r].ID=r; 
       } 
      } 

      int main() 
      { 
       makeExampleStruct(); 
       cout << exampleObj[1].ID << endl; 
       return 0; 
      } 

這給了我一個''exampleObj'沒有在這個範圍內聲明。我知道我可以簡單地在main中聲明對象的創建,但是我寧願將它放在函數內部,這樣就更容易閱讀。有沒有辦法做到這一點?

謝謝您的幫助

回答

1

嘗試聲明全局變量(函數外部) 使用該函數更改全局變量。

函數內部聲明的變量只能在該函數中訪問;它們被稱爲local variables,因爲它們是聲明它們的函數的局部。

main()函數不能訪問另一個函數的局部變量。

全局聲明的變量在任何地方都是可見的。

0

號你需要聲明它的功能外否則是本地的。

0

函數被調用後,你的陣列不再存在:

void makeExampleStruct() 
{ 
    exampleStruct exampleObj[30]; 
     // exampleObj is created here 

    for (int r=0;r<=30;r++) 
    { 
     exampleObj[r].ID=r; 
    } 

    // exampleObj is destroyed here. 
} 

所以,即使你可以訪問對象時,它是非法的函數返回後這樣做,因爲對象的生命週期已經結束。

0

您不能從函數提供對局部變量的全局訪問。你可以做的事情就像是讓他們static,並返回一個參考:

exampleStruct[30]& makeExampleStruct() { 
    static exampleStruct exampleObj[30]; 
    static bool isinitialized = false; 

    if(!isinitialized) { 
      for (int r=0;r<=30;r++) { 
       exampleObj[r].ID=r; 
      } 
      isinitialized = true; 
    } 

    return exampleObj; 
}