友元是一種定義在類外部的普通函式或類,但它需要在類體內進行說明,為了與該類的成員函式加以區別,在說明時前面加以關鍵字friend。友元不是成員函式,但是它可以訪問類中的私有成員。
基本介紹
- 中文名:友元
- 外文名:friend
- 目的:提高程式的運行效率
- 性質:定義在類外部的普通函式或類
- 學科:計算機科學、測繪科學
- 缺點:破壞了類的封裝性和隱藏性
研究背景
友元函式
特點
套用實例
#include<iostream>#include<cmath>using namespace std;class Point{public: Point(double xx, double yy) { x = xx; y = yy; }; void Getxy(); friend double Distance(Point &a, Point &b);private: double x, y;};void Point::Getxy(){ cout << "(" << x << "," << y << ")" << endl;}double Distance(Point &a, Point &b){ double dx = a.x - b.x; double dy = a.y - b.y; return sqrt(dx*dx + dy*dy);}int main(void){ Point p1(3.0, 4.0), p2(6.0, 8.0); p1.Getxy(); p2.Getxy(); double d = Distance(p1, p2); cout << "Distance is" << d << endl; return 0;}友元類
定義
注意事項
問題
class Window;class Screen{public://copy是類Screen的成員
Screen& copy(Window&);//...};
class Window{//copy是類Window的一個友元
friend Screen& Screen::copy(Window&);//...
};
class Window;class Screen{friend class Window;//...};Screen 類的非公有成員現在可以被Window 的每個成員函式訪問。Screen 類的非公有成員現在可以被Window 的每個成員函式訪問。
