Bruce.yang的嵌入式之旅
阿新 • • 發佈:2019-01-03
友元函式是一種特殊的函式,它必須要在類中進行宣告,但其本身並不是類的成員函式,但友元函式可以訪問類的私有成員變數。
友元函式的好處:
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