p182
程序说明:基类Base的成员函数print()是另一个类another的友元函数,所以再print()中可以访问another的私有成员变量aaa。类Derived是类Base的派生类,他从类Base继承了print()函数。也就是说,通过Derived对象也能调用print()函数访问another的私有成员aaa。 //在主函数中,通过类Base的变量a调用print()函数,调用的是基类中定义的版本。输出结果是Base:10。
#include <iostream> using namespace std; class another; // 前向引用声明 class Base //基类 { private: float x; public: void print(const another& K); }; class Derived :public Base//派生类 { private: float y; }; class another //其他类 { private: int aaa; public: another() { aaa = 100; } friend void Base::print(const another& K);//基类的成员函数声明为本类的友元 }; void Base::print(const another& K) { cout << "Base:" << K.aaa << endl;//可以访问私有成员变量 } int main() { Base a; Derived d; another ano;//将aaa初始化为100 a.print(ano);//输出:Base:100 d.print(ano);//输出:Base:100 return 0; //程序说明:基类Base的成员函数print()是另一个类another的友元函数,所以再print()中可以访问another的私有成员变量aaa。类Dericved是类Base的派生类,他从类Base继承了print()函数。也就是说,通过Derived对象也能调用print()函数访问another的私有成员aaa。 //在主函数中,通过类Base的变量a调用print()函数,调用的是基类中定义的版本。输出结果是Base:10。 }
通过派生类Derived的对象d调用print()函数因为没有重写所以执行的是继承自基类Base的版本,输出的内容依旧是Base:100 。
如果派生类Derived中重写了print()函数,若还想在函数中访问another的成私有成员,则必须将类Derived的print()函数也声明为another的友元。在类another中需要添加如下的声明。
friend void Derived::print(const another &K);//派生类的成员函数声明为本类的友元
类Derived中的print()函数定义如下:
void Derived::print(const another &K) { cout << "Drived: << K.aaa << endl; }
此时再通过派生类Derived的对象d调用print()函数,执行的也将是派生类中的版本,
此时输出内容是Derived:100。通过基类对象a调用print()函数时输出维持原样。
如果基类中的成员是静态的,则在其派生类中,被继承的成员也是静态的,即其静态属性随静态成员被继承。
如果基类的静态成员是共有或者保护的,则它们被其派生类继承为派生类的静态成员。
访问这些成员时,通常用“<类名>::<成员名>”的方式去调用,无论有多少个对象被创建,这些成员都只有一个拷贝,他为基类和派生类的所有对象所共享。