C++ 友元

12 阅读1分钟

C++友元

友元(friend)是 C++ 中的一种机制,允许一个非成员函数其他类访问某个类的 private 和 protected 成员。

1.全局函数做友元

#include <iostream>
using namespace std;

class Home
{
    //写在类的最上方,表示下面所有的函数都是Home类的好朋友,可以访问Home类中的私有成员
    friend void goodFriend(Home* home);
public:
    Home()
    {
        livingRoom = "客厅";
        bedRoom = "卧室";
    }

public:
    string livingRoom;

private:
    string bedRoom;
};

void goodFriend(Home* home)
{
    cout << "好友正在访问:" << home->livingRoom << endl;
    //可以访问私有属性
    cout << "好友正在访问:" << home->bedRoom << endl;
};

int main() {
    Home myHome;
    goodFriend(&myHome);
    return 0;
}

友元类

#include <iostream>
using namespace std;

class Home {
    friend class GoodFriend;
public:
    Home() {
        livingRoom = "客厅";
        bedRoom = "卧室";
    }

public:
    string livingRoom;
private:
    string bedRoom;
};

class GoodFriend {
public:
    goodFriend() {
        home = new Home;
    };
    //参观函数,访问home类中的属性
    void visit() { 
        cout << "好朋友正在访问:" << home->livingRoom << endl;
        cout << "好朋友正在访问:" << home->bedRoom << endl;
    };
    Home* home;
};

int main() {
    GoodFriend gf;
    gf.visit();
    return 0;
}

成员函数做友元

#include <iostream>
//#include <string>
using namespace std;

class Home;

class GoodFriend {
public:
    GoodFriend();
    void visit();
    Home* home;
};

class Home {
    //将visit函数指定为Home类的好朋友
    friend void GoodFriend::visit(); 
public:
    Home() {
        livingRoom = "客厅";
        bedRoom = "卧室";
    }

public:
    string livingRoom;
private:
    string bedRoom;
};

//必须放在类外面
GoodFriend::GoodFriend() { 
    home = new Home;
}
//必须放在类外面
void GoodFriend::visit() {
    cout << "好朋友正在访问:" << home->livingRoom << endl;
    cout << "好朋友正在访问:" << home->bedRoom << endl;
};

int main() {
    GoodFriend gf;
    gf.visit();

    return 0;
}