C++ 友元函数与友元类

友元函数定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。

尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数。调用友元函数不需要通过对象和指针作为句柄。

class Box {
   double width;
public:
   friend void printWidth( Box box );
   void setWidth( double wid );
};
void printWidth( Box box ) {
   cout << "Width of box : " << box.width <<endl;
}

友元也可以是一个类,该类被称为友元类,在这种情况下,整个类及其所有成员都是友元。

class Box {
    double width;
public:
    friend void printWidth(Box box);
    friend class BigBox;
    void setWidth(double wid);
};

class BigBox {
public :
    void Print(int width, Box &box) {
        box.setWidth(width);
        cout << "Width of box : " << box.width << endl;
    }
};

注意友元函数和友元类的声明都要在成员被使用的类中定义。换言之,只能主动开放,不能外部强上。

参数传递

友元函数没有this指针,要访问非static成员时,需要对象做参数;要访问static成员或全局变量时,则不需要对象做参数。