歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 友元函數的簡單使用(C++實現)

友元函數的簡單使用(C++實現)

日期:2017/3/1 11:10:56   编辑:Linux編程
友元函數是指某些雖然不是類成員卻能夠訪問類的所有成員的函數類授予它的友元函數特別的訪問權。
定義格式:friend <返回類型> <函數名> (<參數列表>);
  1. //friend.cc
  2. #include <iostream>
  3. #include <cstring>
  4. using namespace std;
  5. class Student
  6. {
  7. private:
  8. int no;
  9. char name[20];
  10. public:
  11. Student(int, const char*);
  12. friend void print(const Student&);
  13. friend ostream& operator<<(ostream&, const Student&);
  14. };
  15. Student::Student(int no, const char *name)
  16. {
  17. this->no = no;
  18. //name是一個char類型的數組,故不能直接用stu.name = "hahaya"進行賦值
  19. strcpy(this->name, name);
  20. }
  21. void print(const Student &stu)
  22. {
  23. cout << "學號:" << stu.no << "姓名:" << stu.name << endl;
  24. }
  25. ostream& operator<<(ostream &os, const Student &stu)
  26. {
  27. os << "學號:" << stu.no << "姓名:" << stu.name;
  28. return os;
  29. }
  30. int main()
  31. {
  32. Student stu(1, "hahaya");
  33. print(stu);
  34. cout << stu << endl;
  35. return 0;
  36. }
程序運行結果:

在friend.cc中定義了兩個友元函數,從這兩個函數中不難發現:一個類的友元函數可以訪問該類的私有成員。其中重載的"<<"操作符必須定義為友元函數,因為輸出流os對象會調用Student類中的私有成員。如果不定義為友元函數,則類外對象不能調用該類的私有成員。
Copyright © Linux教程網 All Rights Reserved