友元函數(shù)是一種特殊的函數(shù),它必須要在類中進(jìn)行聲明,但其本身并不是類的成員函數(shù),但友元函數(shù)可以訪問類的私有成員變量。
友元函數(shù)的好處:
1、實現(xiàn)類之間的數(shù)據(jù)共享
2、提高程序運行效率,方便編程
友元函數(shù)的壞處:
1、破壞數(shù)據(jù)的隱蔽性和類的封裝性
2、降低了程序的可維護(hù)性
所有,友元函數(shù)應(yīng)當(dāng)謹(jǐn)慎的去使用它。
實例:
#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) ; //聲明友元函數(shù) 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 ; }//注意,友元函數(shù)不是類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 ;}運行結(jié)果:
YYX
24
N
86
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對VEVB武林網(wǎng)的支持。
新聞熱點
疑難解答