C++快速入门 第二十讲:一种特殊的友情关系——友元关系
友元关系是类之间的一种特殊关系,这种关系不仅允许友元类访问对方的public方法和属性,还允许友元访问对方的protected和private方法和属性。
实例1:友元关系访问保护量
1 #include <iostream>2 #include <string>3 4 using namespace std;5 class Lovers//爱人关系,基类 6 {7 public:8 Lovers(string theName);//9 void kiss(Lovers *lover); 10 void ask(Lovers *lover, string something); 11 12 protected: 13 string name; 14 15 friend class Others; //祸根,交友不慎。。。。 (友元关系),则Others可以访问name 16 }; 17 18 class Boyfriend:public Lovers//Boyfriend子类,继承Lovers基类 19 { 20 public: 21 Boyfriend(string theName); 22 }; 23 class Girlfriend:public Lovers//girlfriend子类,继承Lovers基类 24 { 25 public: 26 Girlfriend(string theName); 27 }; 28 29 class Others//Others类 ,并没继承Lovers基类 30 { 31 public: 32 Others(string theName); 33 void kiss(Lovers *lover); 34 35 protected: 36 string name; 37 }; 38 39 Lovers::Lovers(string theName)//Lovers类的构造函数 40 { 41 name = theName; 42 } 43 void Lovers::kiss(Lovers *lover)//Lovers *lover表示定义Lovers类的一个对象*lover 44 { 45 cout << name << "亲亲我们家的" << lover->name << endl; 46 } 47 void Lovers::ask(Lovers *lover,string something) 48 { 49 cout << "宝贝儿" << lover->name << "帮我" << something << endl; 50 } 51 Boyfriend::Boyfriend(string theName):Lovers(theName) 52 { 53 } 54 Girlfriend::Girlfriend(string theName):Lovers(theName) 55 { 56 } 57 Others::Others(string theName) 58 { 59 name = theName; 60 } 61 void Others::kiss(Lovers *lover) 62 { 63 cout << name << "亲一下" << lover->name << endl; 64 } 65 int main() 66 { 67 Boyfriend boyfriend("A君"); 68 Girlfriend girlfriend("B妞"); 69 70 Others others("路人甲"); 71 72 girlfriend.kiss(&boyfriend); 73 girlfriend.ask(&boyfriend,"洗衣服啦"); 74 75 cout << "\n当当当当!传说中的路人甲登场啦。。。。\n"; 76 others.kiss(&girlfriend); 77 78 return 0; 79 }