面向对象编程中,友元函数(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

外部链接

Wikiwand in your browser!

Seamless Wikipedia browsing. On steroids.

Every time you click a link to Wikipedia, Wiktionary or Wikiquote in your browser's search results, it will show the modern Wikiwand interface.

Wikiwand extension is a five stars, simple, with minimum permission required to keep your browsing private, safe and transparent.