类与对象中的友元

简介: 类与对象中的友元

在程序里,有些私有属性也想要内外特殊的一些函数或者类进行访问,就需要用到友元技术。

友元的目的就是让一个函数或者类访问另一个类中私有成员

友元关键字: friend

友元的三种实现:

  • 全局函数做友元
  • 类做友元
  • 成员函数做友元
  1. 全局函数做友元

当内外函数访问类内私有成员属性时,编译器会提示错误,如果想要类外函数访问类内私有成员。需要在类中进行友元函数的声明

代码演示:

//建筑物类
class Building
{
    //goodGay全局函数时Building好朋友,可以访问Building中的私有成员
    friend void goodGay(Building* building);
public:
    Building()
    {
        m_SittingRoom = "客厅";
        m_BedRoom = "卧室";
    }
public:
    string m_SittingRoom;  //客厅
private:
    string m_BedRoom;   //卧室
};
//全局函数
void goodGay(Building *building)
{
    cout << "好基友全局函数正在访问:" << building->m_SittingRoom << endl;
    cout << "好基友全局函数正在访问:" << building->m_BedRoom << endl;
}
void test01()
{
    Building building;
    goodGay(&building);
}
int main()
{
    test01();
    return 0;
}

2.类做友元

class Building;
class GoodGay
{
public:
    GoodGay();
    void visit();//参观函数 访问Building中的属性
    Building* building;
};
class Building
{
    //GoodGay类是本类的好朋友,可以访问本类中私有成员
    friend class GoodGay;
public:
    Building();
public:
    string m_SittingRoom;
private:
    string m_BedRoom;
};
//类外写成员函数
Building::Building()
{
    m_SittingRoom = "客厅";
    m_BedRoom = "卧室";
}
GoodGay::GoodGay()
{
    //创建建筑物对象
    building = new Building;
}
void GoodGay::visit()
{
    cout << "好基友类正在访问:" << building->m_SittingRoom << endl;
    cout << "好基友类正在访问:" << building->m_BedRoom << endl;
}
void test01()
{
    GoodGay gg;
    gg.visit();
}
int main()
{
    test01();
    return 0;
}

3.成员函数做友元

class Building;
class GoodGay
{
public:
    GoodGay();
    void visit();  //让visit函数可以访问Building中私有成员
    void visit2(); //让visit2函数不可以访问Building中私有成员
    Building* building;
};
class Building
{
    friend void GoodGay::visit();
public:
    Building();
public:
    string m_SittingRoom;     //客厅
private:
    string m_BedRoom;        //卧室
};
//类外实现成员函数
Building::Building()
{
    m_SittingRoom = "客厅";
    m_BedRoom = "卧室";
}
GoodGay::GoodGay()
{
    building = new Building;
}
void GoodGay::visit()
{
    cout << "visit 函数正在访问:" << building->m_SittingRoom << endl;
    cout << "visit 函数正在访问:" << building->m_BedRoom << endl;
}
void GoodGay::visit2()
{
    cout << "visit2 函数正在访问:" << building->m_SittingRoom << endl;
    //cout << "visit 函数正在访问:" << building->m_BedRoom << endl;
}
void test01()
{
    GoodGay gg;
    gg.visit();
    gg.visit2();
}
int main()
{
    test01();
    return 0;
}
目录
相关文章
|
7月前
|
程序员 C++
29 C++ - 友元
29 C++ - 友元
31 0
|
15天前
|
C++
友元
友元
8 0
|
16天前
|
C++
C++程序中的友元
C++程序中的友元
7 2
|
21天前
|
C++
【C++】类和对象(五)友元、内部类、匿名对象
【C++】类和对象(五)友元、内部类、匿名对象
|
21天前
|
C++
c++类和对象一静态成员的讲解
c++类和对象一静态成员的讲解
13 0
c++类和对象一静态成员的讲解
|
21天前
|
C++
C++类与对象【友元】
C++类与对象【友元】
|
21天前
|
C++
38友元
38友元
11 0
|
21天前
|
存储 C++
C++类与对象【多态】
C++类与对象【多态】
|
21天前
|
C++
【c++】友元
【c++】友元
【c++】友元
|
21天前
|
存储 NoSQL C++
『 C++类与对象 』多继承与虚继承
『 C++类与对象 』多继承与虚继承

热门文章

最新文章