朋友班 friend类可以访问声明为friend的其他类的私有和受保护成员。允许特定类访问其他类的私有成员有时很有用。例如,可以允许LinkedList类访问节点的私有成员。
CPP
class Node { private : int key; Node* next; /* Other members of Node Class */ // Now class LinkedList can // access private members of Node friend class LinkedList; }; |
友元函数 和friend类一样,friend函数可以被授予访问私有和受保护成员的特殊权限。好友功能可以是: a) 另一个阶级的成员 b) 全局函数
CPP
class Node { private : int key; Node* next; /* Other members of Node Class */ friend int LinkedList::search(); // Only search() of linkedList // can access internal members }; |
下面是关于friend函数和类的一些要点: 1) 朋友只能用于有限的目的。太多的函数或外部类被声明为具有受保护或私有数据的类的朋友,这降低了在面向对象编程中封装单独类的价值。 2) 友谊不是相互的。如果A类是B的朋友,那么B不会自动成为A的朋友。 3) 友谊不是遗传的(参见 这 更多细节) 4) Java中没有朋友的概念。 一个简单完整的C++类演示朋友类程序
CPP
#include <iostream> class A { private : int a; public : A() { a = 0; } friend class B; // Friend Class }; class B { private : int b; public : void showA(A& x) { // Since B is friend of A, it can access // private members of A std::cout << "A::a=" << x.a; } }; int main() { A a; B b; b.showA(a); return 0; } |
输出:
A::a=0
一个简单完整的C++程序演示另一个类的朋友功能
CPP
#include <iostream> class B; class A { public : void showB(B&); }; class B { private : int b; public : B() { b = 0; } friend void A::showB(B& x); // Friend function }; void A::showB(B& x) { // Since showB() is friend of B, it can // access private members of B std::cout << "B::b = " << x.b; } int main() { A a; B x; a.showB(x); return 0; } |
输出:
B::b = 0
一个简单完整的C++程序演示全局朋友
CPP
#include <iostream> class A { int a; public : A() { a = 0; } // global friend function friend void showA(A&); }; void showA(A& x) { // Since showA() is a friend, it can access // private members of A std::cout << "A::a=" << x.a; } int main() { A a; showA(a); return 0; } |
输出:
A::a = 0
参考资料: http://en.wikipedia.org/wiki/Friend_class http://en.wikipedia.org/wiki/Friend_function http://www.cprogramming.com/tutorial/friends.html http://www.parashift.com/c++-常见问题解答/朋友和营地。html 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。