1.友元(激情四射的机油)
友元关系:是不同类间的一种特殊关系,这种特殊关系允许友元类访问对方的protected和private方法和属性。
class Lovers { public: Lovers(std::string theName); void kiss(Lovers *lover); void ask(Lovers *lover,std::string something); protected: std::string name; friend class Others;//定义友元,交友了,所以可以访问Lover->name }; class Boyfriend:public Lovers { public: Boyfriend(std::string theName); }; class Girlfriend:public Lovers { public: Girlfriend(std::string theName); }; class Others { public: Others(std::string theName); void kiss(Lovers *lover); protected: std::string name; }; void Lovers::kiss(Lovers *lover) { std::cout << name << "亲亲我们家的" << lover->name << std::endl; } void Lovers::ask(Lovers *lover, std::string something) { std::cout << "宝贝儿" << lover->name << "帮我" << something << std::endl; } /** * *构造器 */ Lovers::Lovers(std::string theName) { name = theName; } Boyfriend::Boyfriend(std::string theName) :Lovers(theName) { } Girlfriend::Girlfriend(std::string theName):Lovers(theName) { } Others::Others(std::string theName) { name = theName; } void Others::kiss(Lovers *lover) { //lover->name是受保护的,不是Lover的子类根本使用不了的。(友元就解决的该问题了) std::cout << name << "亲一下" << lover->name << std::endl; } int main(int argc, const char * argv[]) { Boyfriend boyfriend("A君"); Girlfriend girlfriend("B妞"); Others others("路人甲"); girlfriend.kiss(&boyfriend); girlfriend.ask(&boyfriend,"洗衣服啦"); std::cout << "\n当当当当!传说中的路人甲登场.........\n"; others.kiss(&girlfriend); return 0; }
控制台返回的结果:
B妞亲亲我们家的A君
宝贝儿A君帮我洗衣服啦
当当当当!传说中的路人甲登场.........
路人甲亲一下B妞
原文地址:http://www.cnblogs.com/huen/p/3822224.html