關于C++友元函數的實現講解
更新時間:2018年12月20日 09:43:17 作者:Engineer-Bruce_Yang
今天小編就為大家分享一篇關于關于C++友元函數的實現講解,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
友元函數是一種特殊的函數,它必須要在類中進行聲明,但其本身并不是類的成員函數,但友元函數可以訪問類的私有成員變量。
友元函數的好處:
1、實現類之間的數據共享
2、提高程序運行效率,方便編程
友元函數的壞處:
1、破壞數據的隱蔽性和類的封裝性
2、降低了程序的可維護性
所有,友元函數應當謹慎的去使用它。
實例:
#include <iostream>
#include <cstring>
using namespace std ;
class Student
{
private :
string name ;
int age ;
char sex ;
int score ;
public :
Student(string name , int age , char sex , int score) ;
//聲明友元函數
friend void display_information(Student &Stu);
};
Student::Student(string name , int age , char sex , int score)
{
this->name = name ;
this->age = age ;
this->sex = sex ;
this->score = score ;
}
//注意,友元函數不是類Student的成員,但可以訪問類中的私有成員變量
void display_information(Student &Stu)
{
cout << Stu.name << endl ;
cout << Stu.age << endl ;
cout << Stu.sex << endl ;
cout << Stu.score << endl ;
}
int main(void)
{
Student STU1("YYX",24,'N',86);
display_information(STU1);
return 0 ;
}
運行結果:
YYX
24
N
86
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接

