友元函数的简单使用(C++实现)


友元函数是指某些虽然不是类成员却能够访问类的所有成员的函数类授予它的友元函数特别的访问权。
定义格式:friend <返回类型> <函数名> (<参数列表>);
  1. //friend.cc   
  2. #include <iostream>   
  3. #include <cstring>   
  4. using namespace std;  
  5.   
  6.   
  7. class Student  
  8. {  
  9.     private:  
  10.     int no;  
  11.     char name[20];  
  12.     public:  
  13.     Student(intconst char*);  
  14.     friend void print(const Student&);  
  15.     friend ostream& operator<<(ostream&, const Student&);  
  16. };  
  17.   
  18.   
  19. Student::Student(int no, const char *name)  
  20. {  
  21.     this->no = no;  
  22.     //name是一个char类型的数组,故不能直接用stu.name = "hahaya"进行赋值   
  23.     strcpy(this->name, name);  
  24. }  
  25.   
  26.   
  27. void print(const Student &stu)  
  28. {  
  29.     cout << "学号:" << stu.no << "姓名:" << stu.name << endl;  
  30. }  
  31.   
  32.   
  33. ostream& operator<<(ostream &os, const Student &stu)  
  34. {  
  35.     os << "学号:" << stu.no << "姓名:" << stu.name;  
  36.     return os;  
  37. }  
  38.   
  39.   
  40. int main()  
  41. {  
  42.     Student stu(1, "hahaya");  
  43.   
  44.   
  45.     print(stu);  
  46.     cout << stu << endl;  
  47.   
  48.   
  49.     return 0;  
  50. }  
程序运行结果:

        在friend.cc中定义了两个友元函数,从这两个函数中不难发现:一个类的友元函数可以访问该类的私有成员。其中重载的"<<"操作符必须定义为友元函数,因为输出流os对象会调用Student类中的私有成员。如果不定义为友元函数,则类外对象不能调用该类的私有成员。

相关内容