C++——友元函数&内联函数

C++——友元函数&内联函数

友元函数

类的友元函数是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数。

友元可以是一个函数,该函数被称为友元函数;友元也可以是一个类,该类被称为友元类,在这种情况下,整个类及其所有成员都是友元。

如果要声明函数为一个类的友元,需要在类定义中该函数原型前使用关键字 friend,如下所示:

  1. class Box
  2. {
  3. double width;
  4. public:
  5. double length;
  6. friend void printWidth( Box box );
  7. void setWidth( double wid );
  8. };
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class Box
  6. {
  7. double width;
  8. public:
  9. friend void printWidth( Box box );
  10. void setWidth( double wid );
  11. };
  12.  
  13. // 成员函数定义
  14. void Box::setWidth( double wid )
  15. {
  16. width = wid;
  17. }
  18.  
  19. // printWidth() 不是任何类的成员函数
  20. void printWidth( Box box )
  21. {
  22. /* 因为 printWidth() 是 Box 的友元,它可以直接访问该类的任何成员 */
  23. cout << "Width of box : " << box.width <<endl;
  24. }
  25.  
  26. // 程序的主函数
  27. int main( )
  28. {
  29. Box box;
  30.  
  31. // 使用成员函数设置宽度
  32. box.setWidth(10.0);
  33.  
  34. // 使用友元函数输出宽度
  35. printWidth( box );
  36.  
  37. return 0;
  38. }
  39. /*输出结果是
  40. Width of box : 10
  41. */
posted @ 2021-02-12 12:14  py2020  阅读(148)  评论(0)    收藏  举报