友元函数

本页使用了标题或全文手工转换
维基百科,自由的百科全书

物件導向程式設計中,友誼函數(friend function)是一個指定類別(class)的“朋友”,该函數被允許存取該類別中private、protected、public的資料成員。普通的函數並不能存取private和protected的資料成員,然而宣告一个函數成为一個類別的友誼函數則被允許存取private以及protected的資料成員。

友誼函數的宣告可以放在類別宣告的任何地方,不受存取限定关键字private、protected、public的限制。一个相似的概念是友誼類別英语friend class

友誼關鍵字應該谨慎使用。如果一个拥有private或者protected成员的類別,宣告過多的友誼函數,可能會降低封装性的價值,也可能對整個設計框架產生影響。

應用[编辑]

當一個函數需要存取两個不同類型对象的私有資料成員的时候,可以使用友誼函數。有兩種使用的方式:

  • 该函数作为全域函数,在两个類別中被宣告为友誼函数
  • 作为一个類別中的成员函数,在另一个類別中被宣告为友誼函数
#include <iostream>
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 << "Show via function member of Aazaa" << endl;
  cout << "Aazaa::a = " << x.a << endl;
  cout << "Bezaa::b = " << y.b << endl;
}

// Friend for Aazaa and Bezaa, definition of global function
void show(Aazaa& x, Bezaa& y)
{
  cout << "Show via global function" << endl;
  cout << "Aazaa::a = " << x.a << endl;
  cout << "Bezaa::b = " << y.b << endl;
}

int main()
{
   Aazaa a;
   Bezaa b;

   show(a,b);
   a.show(a,b);
}

参考文献[编辑]

  • 《The C++ Programming Language》 by Bjarne Stroustrup

外部链接[编辑]