完整代码如下:
#includeusing namespace std; class AA { private: int a; public: AA() { a = 100; } friend void Show(AA& ra); //在类内声明 函数前加friend的函数 Show AA会识别Show 为友元函数 //Show可以用AA类内的私有成员 friend class BB;//友元类 单向的 public: //void Show(BB& rb) //{ // //cout << rb.b << endl; // //BB没识别AA为朋友 因此友元类是单向的 //} }; void Show(AA&ra) { cout << ra.a << endl; } class BB { private: int b; public: void Show(AA& ra) { cout << ra.a << endl; } //友元关系不能被继承 }; class SAA :public AA { private : int aa; }; int main() { AA a; //a.a = 200; BB b; b.Show(a); return 0; }



