MichaelBlog

double i = Double.MAX_VALUE; while(i == i + 1){ System.out.print ("学无止境");};

导航

C++: 友元friend三种用法

友元 friend

让类外一些函数或者类访问私有属性,就需要使用友元。

🎈🎈友元的三种实现:

  • 全局函数做友元
  • 类做友元
  • 成员函数做友元
#include <iostream>
#include <string>

using namespace std;

class Building
{
    friend void goodGay(Building* building); //声明友元函数
public:
    Building()
    {
        m_SittingRoom = "客厅";
        m_Bedroom = "卧室";
    }
    string m_SittingRoom;

private:
    string m_Bedroom;

};

//全局函数
void  goodGay(Building* building) {
    cout << "SittingRoom"<<building->m_SittingRoom<< endl;
    cout << "BedRoom" << building->m_Bedroom << endl;
}

void test1() {
    Building building;
    goodGay(&building);
}
int main(){
    test1();
   
    system("pause");
    return 0;

}

类外友元

#include <iostream>
#include <string>

using namespace std;
class Building;
class MyFriend
{
public:

    MyFriend();
    void visit();//访问Building中的属性

    Building* building;//声明Building类型指针building

};
class Building {
    friend class MyFriend;//类外友元
public:
    Building();

public:
    string m_SittingRoom;

private:
    string m_BedRoom;
};

//类外写成员函数
Building::Building() { 
    m_SittingRoom = "SittingRoom";
    m_BedRoom = "BedRoom";
}

MyFriend::MyFriend() {
    building = new Building;//堆中创建新对象

}
void MyFriend::visit()
{
    cout << "MyFriend is visiting " << building->m_SittingRoom << endl;
    cout << "MyFriend is visiting " << building->m_BedRoom << endl;
}

void test()
{
    MyFriend mick;
    mick.visit();
}
int main() {
    test();
    system("pause");
    return 0;

}


成员函数做友元

#include <iostream>
#include <string>

using namespace std;
class Building;
 class MyFriend{
 public:
     GoodGay();

     void visit();
     void visit1();
     Building* building;
};
 class Building
 {
     friend void MyFriend::visit();
     friend void MyFriend::visit1();
 public:
     Building();
 public:
     string m_SittingRoom;

 private:
     string m_BedRoom;

 };

 Building::Building()
 {
     m_SittingRoom = "SittingRoom";
     m_BedRoom = "BedRoom";
 }

 MyFriend::MyFriend()
 {
     building = new Building;

 }
 void  MyFriend::visit()
 {
     cout << "MyFriend is visiting " << building->m_SittingRoom << endl;
     cout << "MyFriend is visiting " << building->m_BedRoom << endl;
 }
 void  MyFriend::visit1()
 {
     cout << "MyFriend is visiting " << building->m_SittingRoom << endl;
     cout << "MyFriend is visiting " << building->m_BedRoom << endl;
 }

 void test1()
 {
     MyFriend Kite;
     Kite.visit();
     Kite.visit1();
 }
int main() {
    test1();

    system("pause");
    return 0;

}

posted on 2022-04-16 09:47  Michael_chemic  阅读(75)  评论(0编辑  收藏  举报