当基类中的函数被protected的时候,只有继承的子类才能访问,为了使得非继承的类也可以使用,使用friend class (类名)来进行操作
#include <iostream> using namespace std; class Lover{ public: Lover(string theName); void kiss(Lover *lover); void ask(Lover *lover, string something); protected: string name; friend class Others; //构造友元函数, 使得Others可以调用name属性 }; Lover::Lover(string theName) { name = theName; } void Lover::kiss(Lover *lover) { cout << name << "kiss" << lover->name << endl; } void Lover::ask(Lover *lover, string something){ cout << name << "ask" << lover->name << "do" << something << endl; } class Boyfriend:public Lover { public: Boyfriend(string theName); }; Boyfriend::Boyfriend(string theName) : Lover(theName){ //进行有参数的继承 } class Girlfriend:public Lover { public: Girlfriend(string theName); }; Girlfriend::Girlfriend(string theName) : Lover(theName){} class Others { public: Others(string theName); void kiss(Lover *lover); protected: string name; }; Others::Others(string theName) { name = theName; } void Others::kiss(Lover *lover) { cout << name << "亲一下" << lover->name << endl; //因为name是protected, 如果没有友元就不能进行访问 } int main() { Boyfriend boyfriend("A君"); Girlfriend girlfriend("B妞"); Others others("路人甲"); girlfriend.kiss(&boyfriend); girlfriend.ask(&boyfriend, "洗衣服啦"); cout << " 当当当:传说的路人甲登场... "; others.kiss(&girlfriend); }