2015-11-01 53 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也不是全局变量,因为它位于主函数内部,无法通过外部函数访问。