:: 的用法小结:
用于将类内声明的静态数据成员在类外初始化;
用于将类内声明的函数成员在类外实现;
用于捞出继承时访问权限被改变的成员,使之还原为原来的权限;
继承时派生类新增了与基类同名的成员,由于同名屏蔽,从而使基类的成员被遮蔽,可用: :将被遮蔽的基类成员重见天日;
用于在类外或子类中访问不继承的静态成员;
用于区分不同名空间的标识符。
:: 的作用之一:恢复访问权
- #include <iostream>
- using namespace std;
- class A
- {
- public:
- A(int xx = 1,int yy = 2){X=xx;Y=yy;}
- int get_XY(){return X*Y;}
- void put_XY(){cout << X << "*" << Y <<"="<< X*Y <<endl;}
- protected:
- int X,Y;
- };
- class B:private A
- {
- public:
- B(int s,int xx,int yy):A(xx,yy),S(s){}
- //A::put_XY;
- A:: get_XY;
- void make_S(){put_XY();cout<<S<<endl;}
- private:
- int S;
- };
-
-
- void main()
- {
- B b(3,5,6);
- b.get_XY();
- //b.put_XY(); 还是private权限,不可以在类外被访问。
- b.make_S();
- }
注意:
恢复时不可带类型名;( int A::get_XY(); 错)
只能恢复不可提升或降低访问权限;
当父类被恢复的函数重载时,将全都恢复;
父类中不同访问域的重载函数不能恢复;
若子类新增了与父类同名的成员,则父类同名的成员不可恢复。
:: 的作用之二:隐藏再现
- #include <iostream>
- using namespace std;
- class A
- {
- public:
- int X,Y;
- };
- class B:public A
- {
- public:
- int Y,Z;
- };
- void main()
- {
- B b;
- b.X= 1;
- b.Y= 2;
- b.A::Y= 3;
- b.Z= 4;
- }
:: 的作用之三:隐藏再现
- #include <iostream>
- using namespace std;
- class A
- {
- public:
- static int i;
- static void Add() { i++; }
- void out() { cout<<"static i = "<<i<<endl; }
- };
- int A::i= 10;
- class B:private A
- {
- public:
- A::out;
- };
- class C:public B
- {
- public:
- void f();
- };
- void C::f()
- {
- //私有继承,化公为私
- //i = 50; // 错
- //Add() ; // 错
- A:: i = 50;
- A:: Add();
- }
- void main()
- {
- A x;
- C y;
- x.Add();
- x.out();
- y.f();
- y.out();
- cout<< "static i = "<<A::i<<endl;
- };