友元函数不是类成员函数,是一个类外的函数,但是可以访问类所有成员。

class Point{
public:
    friend void fun(Point t);//友元函数
private:
    int a;
protected:
    int b;
};

void fun(Point t)
{
    t.a = 100;
    t.b = 2000;
    cout << t.a << "   " << t.b << endl;
}

int main()
{
    Point test;
    fun(test);
    system("pause");
    return 0;
}

运行结果:

友元类:类A是类B的友元类,则A就可以访问B的所有成员(成员函数,数据成员)。(类A,类B无继承关系)

class Point{
    friend class Line;
public:
    void fun()
    {
        this->x = 100;
        this->y = 120;
    }
private:
    int x;
protected:
    int y;
};

class Line{
public:
    void printXY()
    {
        t.fun();
        cout << t.x << "  " << t.y << endl;
    }

private:
    Point t;
};

int main()
{
    Line test;
    test.printXY();
    system("pause");
    return 0;
}

运行结果:

友成员函数:使类B中的成员函数成为类A的友元函数,这样类B的该成员函数就可以访问类A的所有成员(成员函数、数据成员)了

 

 1 class Point;//在此必须对Point进行声明,如不声明将会导致第5行(void fun(Point t);)“Point”报错(无法识别的标识符)
 2 
 3 class Line{
 4 public:
 5     void fun(Point t);
 6     //void Line::fun(Point t)//在此编译器无法获知class Point中到底有哪些成员,所以应在Point后面定义
7 //{ 8 // t.x = 120; 9 // t.y = 130; 10 // t.print(); 11 //} 12 13 }; 14 15 class Point{ 16 public: 17 friend void Line::fun(Point t); 18 Point(){} 19 void print() 20 { 21 cout << this->x << endl; 22 cout << this->y << endl; 23 } 24 private: 25 int x; 26 protected: 27 int y; 28 }; 29 30 void Line::fun(Point t)//应在此定义fun函数 31 { 32 t.x = 120; 33 t.y = 130; 34 t.print(); 35 } 36 37 int main() 38 { 39 Point test; 40 Line LL; 41 LL.fun(test); 42 system("pause"); 43 return 0; 44 }

 运行结果:

总结:关键字“friend”描述的函数就是友元函数,“friend”所在类的所有成员都可被友元函数访问。(带有关键字“friend”的类,就说明这个类有一个好朋友,他的好朋友就是关键字“friend”后面跟的那个函数或类。他的好朋友可以访问他的所有成员  )