引入
當(dāng)某一類或函數(shù)需要訪問或使用另一類的私有函數(shù)或變量時,引入友元。
例如:
你的銀行卡號是私有的,別人不能訪問,但你父母要往里存錢,此時需要你的銀行卡號對其開放訪問,這你的父母便是你的友元。
未引入友元的情況
class A{
public:
....
private:
void Func();
int field;
}
void UseA(A & a)
{
a field = 5; //field為對象a中的私有成員,不能訪問,報錯
}
int main()
{
A a;
UseA(a);
}
友元函數(shù)的使用方法
格式
friend 被當(dāng)作友元的函數(shù)或類
例如:
class A{
friend void UseA(A & a); //聲明友元函數(shù)
public:
....
private:
void Func();
int field;
}
void UseA(A & a)
{
a.field = 5; //正常訪問調(diào)用
...
}
int main()
{
A a;
UseA(a);
}
友元函數(shù)和友元類
-
友元函數(shù)
包括全局函數(shù),和類的成員函數(shù)
-
友元類
包括類的全部成員函數(shù)
-
嵌套類及嵌套的友元類
-
運算符重載時使用
例子如下
class Parent{
public:
void addMoney(Wallet & w){
w.money += 8888;
}
void checkMoney(Wallet & w){
cout<<w.history<<endl;
}
void checkCourse(Course & c){
cout<<c.score<<endl;
}
};
class Wallet{
friend class Parent; //友元聲明一般放在public和private前面
friend void Parent::AddMoney(Wallet &); //可以只限定Parent類中的特定函數(shù)為友元
private:
int money;
int history;
}
class A{
friend const A operator + ( const A & Ihs, const A & rhs);
friend void B::f(A&a);
friend class C;
class D; //嵌套類
friend class D; //聲明嵌套類為友元,此時class D能夠訪問調(diào)用A中的成員
private:
int mValue;
};
補充說明
- 友元的本質(zhì)都是友元函數(shù),沒有友元數(shù)據(jù)
- 友元函數(shù)不是類的成員
- 友元關(guān)系是單向的
即被聲明的友元能訪問當(dāng)前類,但當(dāng)前類不能訪問友元。 - 友元關(guān)系沒有傳遞性
即如果B是A的友元,C是B的友元,則C不是A的友元,C不能訪問A的成員。 - 友元對封裝和信息隱蔽的影響:
- 局部來看,破壞封裝及信息隱蔽
- 全局來看,保護(hù)信息(只限定友元能訪問私有成員)