2020-09-17  本文已影响0人  const_qiu
#include <iostream>
using namespace std;
class Base {
 public:
     void print_test() {
         cout << "hhhh" << endl;
     }
};

int main()
{
    Base const s ;
    s.print_test(); //会报错,print_test()不是常成员函数,
}

在类中把某个函数声明为friend,既可以是private也可以是public

friend 函数破坏了类的封装:

class Base {
 public:
     Base( ) {
         cout << "create a object" << endl;
     }
public:
     friend void test_friend(Base& );
private:
    int base_a = 0; 
};
void test_friend(Base& b) {
    cout << "我是友元函数" <<b.base_a<< endl;
}

int main()
{
    Base  s;
    test_friend(s);
}
上一篇 下一篇

猜你喜欢

热点阅读