Loading

C++友元学习案例

1.全局函数作友元

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

// 友元: 让一个函数或类 访问另一个类的私有成员

class Building{

    // 友元声明
    friend void GoodGay1(Building *building);
    friend void GoodGay2(Building &building);

public:
    // 构造函数
    Building(){
        m_Sittingroom = "客厅";
        m_Bedroom = "卧室";
    }

    string m_Sittingroom;

private:
    string m_Bedroom;
};

// 全局函数 1.传入指针 用->访问属性 由test01()调用
void GoodGay1(Building *building){
    cout << "好基友全局函数正在访问 :" << building->m_Sittingroom << endl;
    cout << "好基友全局函数正在访问 :" << building->m_Bedroom << endl;
}

// 全局函数 2.传入引用 用.访问属性 由test02()调用
void GoodGay2(Building &building){
    cout << "好基友全局函数正在访问 :" << building.m_Sittingroom << endl;
    cout << "好基友全局函数正在访问 :" << building.m_Bedroom << endl;
}

void test01(){
    Building building1;
    GoodGay1(&building1); // 传引用
}

void test02(){
    Building building2;
    GoodGay2(building2); // 直接传对象
}

int main(){
    test01();
    test02();
}

2.类作友元

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

class Building;  // 这里要先声明一下,不然11行会报错

class GoodGay{
public:
    GoodGay(); // 构造函数,类外实现
    void visit(); // 参观函数,访问Building类的属性
    Building * building; // 维护一个指针,即用这个指针去指向Building类的对象
};

class Building{
    // 友元声明
    friend class GoodGay;
public:
    Building(); // 构造函数,类外实现

    string m_Sittingroom;

private:
    string m_Bedroom;
};

// 类外实现成员函数
Building::Building(){
    m_Sittingroom = "客厅";
    m_Bedroom = "卧室";
}

GoodGay::GoodGay(){
    building = new Building;  // 相当于用Building * building来接收创建出来的对象
}

void GoodGay::visit(){
    cout << "好基友类正在访问:"<< building->m_Sittingroom << endl;
    cout << "好基友类正在访问:"<< building->m_Bedroom << endl;
}

void test01(){
    // 调用顺序:GoodGay构造函数,Building构造函数,GoodGay的visit函数
    GoodGay gg;
    gg.visit();
}

int main(){
    test01();
}

3.成员函数作友元

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

// 用一个类的成员函数作为另一个类的友元, 即该成员函数可以访问另一个类的私有内容

class Building;  // 这里要先声明一下,不然14行会报错

class GoodGay{
    public:
    GoodGay();
    void visit1(); // 让此函数可以访问Building类私有成员
    void visit2(); // 让此函数不可以访问Building类私有成员
    Building * building;
};

class Building{
    public:
    friend void GoodGay::visit1();
    Building();
    string m_Sittingroom;
    private:
    string m_Bedroom;
};

// 类外实现成员函数
Building::Building(){
    m_Sittingroom = "客厅";
    m_Bedroom = "卧室";
}

GoodGay::GoodGay(){
    building = new Building;
}

void GoodGay::visit1(){
    cout << "visit1 函数正在访问:" << building->m_Sittingroom << endl;
    cout << "visit1 函数正在访问:" << building->m_Bedroom << endl;
}
void GoodGay::visit2(){
    cout << "visit2 函数正在访问:" << building->m_Sittingroom << endl;
    // cout << "visit2 函数正在访问:" << building->m_Bedroom << endl; 报错
}

void test01(){
    GoodGay gg;
    gg.visit1();
    gg.visit2();
}

int main(){
    test01();
}
posted @ 2022-01-17 19:29  少年人永远倔强  阅读(52)  评论(0编辑  收藏  举报