c++友元函數、友元類、友成員函數


友元函數不是類成員函數,是一個類外的函數,但是可以訪問類所有成員。

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”后面跟的那個函數或類。他的好朋友可以訪問他的所有成員  )

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM