在物件導向程式設計中,友誼函數(friend function)是一個指定類別(class)的“朋友”,该函數被允許存取該類別中private、protected、public的資料成員。普通的函數並不能存取private和protected的資料成員,然而宣告一个函數成为一個類別的友誼函數則被允許存取private以及protected的資料成員。
友誼函數的宣告可以放在類別宣告的任何地方,不受存取限定关键字private、protected、public的限制。一个相似的概念是。
友誼關鍵字應該谨慎使用。如果一个拥有private或者protected成员的類別,宣告過多的友誼函數,可能會降低封装性的價值,也可能對整個設計框架產生影響。
應用
當一個函數需要存取两個不同類型对象的私有資料成員的时候,可以使用友誼函數。有兩種使用的方式:
*该函数作为全域函数,在两个類別中被宣告为友誼函数
*作为一个類別中的成员函数,在另一个類別中被宣告为友誼函数
#include
using namespace std;
class Bezaa; // Forward declaration of class Bezaa in order for example to compile.
class Aazaa
{
private:
int a;
public:
Aazaa() { a = 0; }
void show(Aazaa& x, Bezaa& y);
friend void ::show(Aazaa& x, Bezaa& y); // declaration of global friend
};
class Bezaa
{
private:
int b;
public:
Bezaa() { b = 6; }
friend void ::show(Aazaa& x, Bezaa& y); // declaration of global friend
friend void Aazaa::show(Aazaa& x, Bezaa& y); // declaration of friend from other class
};
// Definition of a member function of Aazaa; this member is a friend of Bezaa
void Aazaa::show(Aazaa& x, Bezaa& y)
{
cout
参考文献
- 《The C++ Programming Language》 by Bjarne Stroustrup
外部链接
*[http://www.codersource.net/c/ctutorials/ctutorialfriend.aspx C++ friend function tutorial] at CoderSource.net
*[http://www.cplusplus.com/doc/tutorial/inheritance.html C++ friendship and inheritance tutorial] at cplusplus.com
评论 (0)