C++ FRIEND 关键词

黎 浩然/ 20 5 月, 2022/ C/C++, 计算机/COMPUTER/ 0 comments

友元函数

#include <iostream>
using namespace std;

class A {
public:
    A(int _a):a(_a){};
    friend int geta(A &ca); ///< 友元函数 private:
    int a; 
};

int geta(A &ca) {
    return ca.a;
}

int main() {
    A a(3);
    cout << geta(a) << endl; // easy to get it!
    return 0;
}

友元类

#include <iostream>
using namespace std;

class A {
public:
    A(int _a):a(_a){};
    friend class B;
private:
    int a; 
};

class B {
public:
    int getb(A &ca) {
        return  ca.a;
    }; 
};

int main() {
    A a(3);
    B b;
    cout << b.getb(a) << endl;
    return 0;
}
  • 假如类B是类A的友元,类C继承于类A,那么友元类B是没办法直接访问类C的私有或保护成员
  • 假如类B是类A的友元,类C是类B的友元,那么友元类C是没办法直接访问类A的私有或保护成员
Share this Post

Leave a Comment

您的邮箱地址不会被公开。 必填项已用 * 标注

*
*