编程语言
首页 > 编程语言> > C++之友元

C++之友元

作者:互联网

友元

类里面的私有属性,可以让类外一些特殊的函数或者类进行访问

关键字:friend

友元三种实现:

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

成员函数为友元

#include <iostream>
using namespace  std;
#include <string>
class Building
{
    //告诉编译器,goodGay是全局函数,是BUIling类的好朋友,可以访问私有
    friend  void goodGay(Building *building);
public:
    Building(){
        m_SittingRoom = "客厅";
        m_BedRoom = "卧室";
    }
    string m_SittingRoom;
private:
    string m_BedRoom;
};

void goodGay(Building *building){
    cout<< building->m_SittingRoom <<building->m_BedRoom << endl;
}
void test01(){
    Building b;
    goodGay(&b);
}
int main(){
    test01();
    return  0;
}

类做友元

#include <iostream>
using namespace  std;
#include <string>
class Building{
    //告诉编译器,goodgay类是building类的好朋友,可以访问里面的私有内容
    friend class Goodgay;
public:
    Building();
public:
    string m_Sit;
private:

    string m_Bed;
};
class Goodgay{
public:
    Goodgay();
    void visit();

private:
    Building *building;
};

//构造函数无需返回值,直接在前面加上作用域
Building ::Building() {
    m_Sit = "客厅";
    m_Bed = "卧室";
}
Goodgay ::Goodgay() {
    building = new Building;//声明对象仅定义,需要给另一个类一个空间
}
//在返回值后面加上作用域
void Goodgay::visit() {
    cout<<building->m_Sit<<building->m_Bed<<endl;
}


void test(){
    Goodgay gg;
    gg.visit();
}
int main(){
    test();
    return  0;
}

成员函数做友元

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

class Building;
class Goodgay{
public:
    Goodgay();
    void visit();//让visit可以访问builing中私有成员
    void visit2();//不可以访问

private:
    //用到该类,必须在其前面声明类,可以虚假声明class Building
    Building *building;//私有部分可以用visit同类访问
};
class Building{
    //告诉编译器,goodgay类下的visit成员函数是该类的好朋友,可以访问里面的私有内容
    friend void Goodgay::visit();//用到该类,必须在其前面声明类,可以虚假声明class Goodgay;
public:
    Building();
public:
    string m_Sit;
private:

    string m_Bed;
};


//构造函数无需返回值,直接在前面加上作用域
Building ::Building() {
    m_Sit = "客厅";
    m_Bed = "卧室";
}
Goodgay ::Goodgay() {
    building = new Building;
}
//在返回值后面加上作用域
void Goodgay::visit() {
    cout<<building->m_Sit<<building->m_Bed<<endl;
}
void Goodgay::visit2() {
    cout<<building->m_Sit<<endl;
}

void test(){
    Goodgay gg;
    gg.visit();
    gg.visit2();
}
int main(){
    test();
    return  0;
}

标签:Building,building,之友,void,visit,C++,Goodgay,class
来源: https://www.cnblogs.com/Eyeui/p/13878953.html