环境:
编译器:CLion2021.3;操作系统:macOS Ventura 13.0.1
在类中定义的成员属性往往是private,外界是无法访问的。若有特殊需求想让外界可以访问这些私有属性,可以把允许访问的这个外界设置为本类的友元。
一、全局函数做友元class Building {//告诉编译器 goodGay全局函数 是 Building类的好朋友,可以访问类中的私有内容
friend void goodGay(Building *building);
public:
string m_SittingRoom; //客厅
private:
string m_BedRoom; //卧室
public:
Building() {this->m_SittingRoom = "客厅";
this->m_BedRoom = "卧室";
}
};
void goodGay(Building *building) {cout<< "好基友正在访问: "<< building->m_SittingRoom<< endl;//ok
cout<< "好基友正在访问: "<< building->m_BedRoom<< endl;//ok,若不将goodGay设为友元则err
}
二、类做友元class Building {//告诉编译器 goodGay类是本类的好朋友,可以访问到Building类中私有内容
friend class goodGay;
public:
string m_SittingRoom; //客厅
private:
string m_BedRoom;//卧室
public:
Building();
};
class goodGay {private:
Building *building;
public:
goodGay();
void visit();//访问Building的属性
};
Building::Building() {//类外实现成员函数
this->m_SittingRoom = "客厅";
this->m_BedRoom = "卧室";
}
goodGay::goodGay() {building = new Building;
}
void goodGay::visit() {cout<< "好基友正在访问"<< building->m_SittingRoom<< endl;//ok
cout<< "好基友正在访问"<< building->m_BedRoom<< endl;//ok
}
三、成员函数做友元class Building {//告诉编译器 goodGay类中的visit成员函数 是Building好朋友,可以访问私有内容
friend void goodGay::visit();
public:
string m_SittingRoom; //客厅
private:
string m_BedRoom;//卧室
public:
Building();
};
class goodGay {private:
Building *building;
public:
goodGay();
void visit(); //只让visit函数作为Building的好朋友,可以发访问Building中私有内容
void visit2();
};
Building::Building() {this->m_SittingRoom = "客厅";
this->m_BedRoom = "卧室";
}
goodGay::goodGay() {building = new Building;
}
void goodGay::visit() {cout<< "好基友正在访问"<< building->m_SittingRoom<< endl;
cout<< "好基友正在访问"<< building->m_BedRoom<< endl;
}
void goodGay::visit2() {cout<< "好基友正在访问"<< building->m_SittingRoom<< endl;
// cout<< "好基友正在访问"<< building->m_BedRoom<< endl;//err,因为只声明了visit是友元而没有把visit2声明为友元
}
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧