C++中,在类外调用类的私有成员函数的两种方式

1. 通过类中的public成员函数调用private成员函数:

  1. #include<iostream>
  2. using namespace std;
  3.  
  4. class Test
  5. {
  6.     public:
  7.         void fun2()
  8.         {
  9.             fun1();
  10.         }
  11.     private:
  12.         void fun1()
  13.         {
  14.             cout<<“fun1″<<endl;
  15.         }
  16. };
  17. int main()
  18. {
  19.     Test t;
  20.     t.fun2();
  21.     return 0;
  22. }

输出结果:
《C++中,在类外调用类的私有成员函数的两种方式》

2.通过类的友元函数调用该类的private成员函数,但是该成员函数必须设为static,这样就可以在友元函数内通过类名调用,否则无法调用:

  1. #include<iostream>
  2. using namespace std;
  3.  
  4. class Test
  5. {
  6.     friend void fun2(); //fun2()设为类Test的友元函数
  7.  private:
  8.      static void fun1()
  9.      {
  10.          cout<<“fun1″<<endl;
  11.      }
  12. };
  13. void fun2()
  14. {
  15.     Test::fun1();
  16. }
  17. int main()
  18. {
  19.     fun2();
  20.     return 0;
  21. }

输出结果:

《C++中,在类外调用类的私有成员函数的两种方式》

    原文作者:Steven_ycs
    原文地址: https://blog.csdn.net/weixin_38208741/article/details/106737916
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞