在类的使用中,我们经常会碰到以下三种情况:
1.类的成员函数的局部变量隐藏了类的同名成员变量,看如对上面程序的分析。 protected: const static int gbs = 5; const static int bbs = -3; float gradescore; public: float GetGS(float goodball,float badball) { int gradescore=0; ballscore::gradescore = (goodball*gbs + badball*bbs) / (goodball + badball); return ballscore::gradescore; } 代码中的int gradescore就把float gradescore给隐藏了,所以要使用成员变量float gradescore的时候必须在其之前加上类名称和域区分符(::)。
2.在类定义外部非类型名隐藏了类型名称的情况,看上面代码的分析! class ballscore { protected: const static int gbs = 5; const static int bbs = -3; float gradescore; public: float GetGS(float goodball,float badball) { int gradescore=0; ballscore::gradescore = (goodball*gbs + badball*bbs) / (goodball + badball); return ballscore::gradescore; } }; int ballscore=0; 代码中的全部变量int ballscore隐藏了类名称class ballscore
所以在main中如如果要定义ballscore类的对象就要在类名称前加上class关键字 class ballscore jeff; 3.类型名称隐藏了非类型名称,看对上面代码的分析 int test; void main() { class test { float a; float b; }; test test; ::test=1; class ballscore jeff; cout<<jeff.GetGS(10,3); cin.get(); } 在普通函数内部定义的类叫做局部类,代码中的test类就是一个局部类!
代码中的test类隐藏了全局变量test如果要操作全局变量test那么就要在test前加上域区分符号(::),进行使用!
::test=1就是对全局变量test进行了赋值操作。 我们最后说一下名字空间!
名字空间就是指某一个名字在其中必须是唯一的作用域.
如果这个定义想不明白,可以简单的说成,在一个区域内,某一个名字在里面使用必须是唯一的,不能出现重复定义的情况出现,这个区域就是名字空间!
|