友元函數是一種特殊的函數,它必須要在類中進行聲明,但其本身并不是類的成員函數,但友元函數可以訪問類的私有成員變量。
友元函數的好處:
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
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答