轉自:友元函數、友元類、訪問私有數據成員、友元關係[C++]:https://www.cnblogs.com/JCSU/articles/1044346.html
一 友元函數(friend function)
1. 什麼是友元函數?
一個類的私有數據成員通常只能由類的函數成員來訪問,而友元函數可以訪問類的私有數據成員,也能訪問其保護成員
2. 友元函數的用處體現在哪裏?
2.1 使用友元函數可提高性能,如:用友元函數重載操作符和生成迭代器類
2.2 用友元函數可以訪問兩個或多個類的私有數據,較其它方法使人們更容易理解程序的邏輯關係
3. 使用友元函數前應注意:
3.1 類的友元函數在類作用域之外定義,但可以訪問類的私有和保護成員
3.2 儘管類定義中有友元函數原型,友元函數仍然不是成員函數
3.3 由於友元函數不是任何類的成員函數,所以不能用句柄(對象)加點操作符來調用
3.4 public, private, protected成員訪問符與友員關係的聲明無關,因此友元關係聲明可在類定義的任何位置,習慣上在類定義的 開始位置
3.5 友元關係是指定的,不是獲取的,如果讓類B成爲類A的友元類,類A必須顯式聲明類B爲自己的友元類
3.6 友元關係不滿足對稱性和傳遞性
3.7 如果一個友元函數想與兩個或更多類成爲友元關係,在每個類中都必須聲明爲友元函數
4. 注:由於C++屬於混合語言,常在同一個程序中採用兩種函數調用且這兩種函數調用往往是相反的。類C語言的調用將
基本數據或對象傳遞給函數,C++調用則是將函數(或信息)傳遞給對象
實例1. 友元函數的聲明、定義與使用
#include <iostream>
using namespace std;
class Car
{
friend void display(Car); //類"Car"的朋友display() //友元函數的聲明
private:
int speed;
char color[20];
public:
void input( )
{
cout<<"Enter the color : ";
cin>>color;
cout<<"Enter the speed : ";
cin>>speed;
}
};
void display(Car x) //友元函數的定義
{
cout<<"The color of the car is : "<<x.color<<endl;
cout<<"The speed of the car is : "<<x.speed<<endl;
}
int main( )
{
Car mine;
mine.input( ); //訪問成員函數
display(mine); //友元函數的使用 //將對象"mine"傳給友元函數
return 0;
}
輸出結果:
Enter the color: green 回車
Enter the speed: 100 回車
The color of the car is : green
The speed of the car is : 100
實例2. 將一個函數聲明爲多個類的友元
#include <iostream>
using namespace std;
class Virus; //類'Virus'未定義前要用到,需事先告訴編譯器'Virus'是一個類
class Bacteria
{
private:
int life;
public:
Bacteria() { life=1; }
friend void Check(Bacteria, Virus); //類'Bacteria'中,將Check聲明爲友元函數
};
class Virus
{
private:
int life;
public:
Virus() : life(0) {}
friend void Check(Bacteria, Virus); //類'Virus'中,將Check聲明爲友元函數
};
void Check (Bacteria b, Virus v) //友元函數的定義
{
if (b.life==1 || v.life==1)
{
cout<<"\nSomething is alive.";
}
if (b.life==1)
{
cout<<"\nA bacteria is alive.";
}
if (v.life==1)
{
cout<<"\nA virus is alive.";
}
}
int main()
{
Bacteria fever;
Virus cholera;
Check(fever, cholera); //友元函數的調用
return 0;
}
輸出結果:
Something is alive.
A bacteria is alive.
二 友元類(friend class)
1. 友元類可以訪問與之爲友元關係的類的所有私有成員
2. 友元類使用較少
實例: 友元類
#include <iostream>
using namespace std;
class Add
{
private:
int x,y;
public:
Add()
{
x=y=4;
}
friend class Support; //類'Support'現在是類'Add'的朋友
};
class Support
{
public:
void Sum(Add ob)//此函數可訪問類'Add'的所有私有成員
{
cout<<"The sum of the 2 members is : "<<(ob.x+ob.y)<<endl;
}
};
int main()
{
Add ad;
Support sup;
sup.Sum(ad);
return 0;
}
輸出結果:
The sum of the 2 members is : 8