- 友元是C++提供的一種破壞數據封裝和數據隱藏的機制
- 通過將一個模塊聲明爲另外一個模塊的友元,一個模塊能夠引用到另一個模塊中本是被隱藏的信息
- 可以聲明友元函數和友元類
- 爲了確保數據的完整性,及數據封裝與隱藏的原則,一般很少用友元
1. 友元函數
友元函數是在類聲明中由關鍵字friend修飾說明的非成員函數,在它的函數體中能夠通過對象名訪問private和protected成員。
作用:增加靈活性,使程序員可以在封裝和快速性方面做合理的選擇。
訪問對象中的成員必須通過對象名。
例:
#include <iostream>
#include<cmath>
using namespace std;
class Point{ //Point類聲明
public:
Point(int x = 0, int y = 0) :x(x), y(y){}
int getX(){ return x; }
int getY(){ return y; }
friend float dist(Point &a, Point &b);
private:
int x, y;
};
float dist(Point &a, Point &b)
{
double x = a.x - b.x;
double y = a.y - b.y;
return static_cast<float>(sqrt(x*x + y*y));
}
int main()
{
Point p1(1, 1), p2(4, 5);
cout << "The distance is: ";
cout << dist(p1, p2) << endl;
system("pause");
return 0;
}
2. 類友元
若一個類爲另外一個類的友元,則此類的所有成員都能訪問對方類的私有成員。
聲明語法:將友元類名在另一個類中使用friend修飾說明。
舉例說明:
class A{
friend class B;
public:
void display(){
cout << x << endl;
}
private:
int x;
};
class B{
public:
void set(int i);
void display();
private:
A a;
};
void B::set(int i){
a.x = i;
}
void B::display(){
a.display();
}
上面的B類中私有成員包含A類的對象a,B類的成員函數定義中想直接調用A類的私有成員x,這個時候就必須進行授權,這個授權就是在A類中將B類聲明爲友元類。
類的友元關係是單向的:聲明B類是A類的友元不等於A類是B類的友元。