2015-11-01 93 views
1

你好我一直在做家庭作業,由於家庭作業規則我不允許使用全局變量。我對全局變量進行了研究,但不能真正理解我的變量是全局變量還是局部變量。變量在我的類的構造函數中定義。這是我的頭看起來像:我的變量是全局的嗎?

#include <string> 
using namespace std; 

class Team{ 
    public: 
     string tColor; 
     string tName; 
}; 
class Player{ 
    public: 
     string pPos; 
     string pName; 
}; 
class SocReg { 
    private: 
     Team *teams;// These are the variables Im not sure of 
     Player *players;// These are the variables Im not sure of 
     int playernum, teamnum; // These are the variables Im not sure of 
    public: 
     SocReg(); 
     ~SocReg(); 
     void addTeam(string teamName, string color); 
     void removeTeam(string teamName); 
     void addPlayer(string teamName, string playerName, string playerPosition); 
     void removePlayer(string teamName, string playerName); 
     void displayAllTeams(); 
     void displayPlayer(string playerName); 
     void displayTeam(string teamName); 
// ... 
// you may define additional member functions and data members, 
// if necessary. 
}; 

這個問題可能提前聲音太noobish但我太糊塗了感謝

+3

您所評論的行不定義*變量*,而是*私有實例成員*,根據定義,它們是非全局的。 –

+2

@FrédéricHamidi:成員變量是變量。 –

+1

爲什麼這些將成爲全球o.O –

回答

2

全局變量的東西,你可以查看和修改由「無處不在」的代碼,即,在任何特定類別之外。

它們被認爲是有害的,因爲當你改變一個全局變量時,你必須以某種方式知道可能看到它的所有代碼,以便知道這種改變會產生什麼效果。這使得很難推斷你的代碼。

所有的變量都封裝在對象中,不是全局的。在C++中,全局變量是在類之外或「靜態」聲明的。

+0

所以你會認爲名稱空間中除全局名稱空間以外的變量是全局變量嗎?這個術語是否由標準支持? – JorenHeit

0

它們都是類定義,沒有聲明變量。

所以沒有全局變量。

例如:

// example.cpp 
int BAR;  
class foo { 
    int bar; 
}; 
foo FOO; 

void f() { 
    BAR = 0; // We can access global variable here 
} 

int main() { 
    foo FOO2; 
    BAR = -1; // We can access global variable here 
    return 0; 
} 

BAR和FOO是全局變量,它們可以進行全局訪問。

class foo { 
    int bar; 
}; 

僅僅是類foo的定義。

main()函數內部的FOO2也不是全局變量,因爲它位於主函數內部,無法通過外部函數訪問。