在程序里,有些私有属性也想让类外特殊的一些函数或者类进行访问,就需要用到友元
友元的目的就是让一个函数或者类 访问另一个类中的私有成员
友元的关键字为 friend
友元的三种体现
把函数声明写进类里,前面加上friend
#include <iostream> #include <string> using namespace std; //建筑物类 class Building { //该全集函数是Building类的友元函数 可以访问私有成员 friend GoodFriend(Building &building); public: Building() { m_SittingRoom = "客厅"; m_BedRoom = "卧室"; } string m_SittingRoom; //客厅 private: string m_BedRoom;//卧室 }; //全局函数 GoodFriend(Building &building) { cout << "全局函数正在访问" << building.m_SittingRoom << endl; cout << "全局函数正在访问" << building.m_BedRoom << endl; } int main() { Building building; GoodFriend(building); }
#include <iostream> #include <string> using namespace std; //建筑物类 class Building { public: friend class GoodFriend;//友元类 Building(); string m_SittingRoom; //客厅 private: string m_BedRoom;//卧室 }; //友元类 class GoodFriend { public: GoodFriend(); void visit(); //参观函数 访问Building中的属性 Building * building; }; //类外写成员函数 Building::Building() { m_SittingRoom = "客厅"; m_BedRoom = "卧室"; } GoodFriend::GoodFriend() { //创建建筑物对象 building = new Building; } void GoodFriend::visit() { cout << "友元类正在访问" << building->m_SittingRoom << endl; cout << "友元类正在访问" << building->m_BedRoom << endl; } int main() { GoodFriend gf; gf.visit(); }
GoodFriend类要写在Building类前面,不然报错
#include <iostream> #include <string> using namespace std; class Building; class GoodFriend { public: GoodFriend(); void visit(); //visit可以访问Building中的私有成员 void visit2(); //visit2不可以访问Building中的私有成员 Building * building; }; //建筑物类 class Building { public: friend void GoodFriend::visit();//成员函数做友元 Building(); string m_SittingRoom; //客厅 private: string m_BedRoom;//卧室 }; //类外写成员函数 Building::Building() { m_SittingRoom = "客厅"; m_BedRoom = "卧室"; } GoodFriend::GoodFriend() { //创建建筑物对象 building = new Building; } void GoodFriend::visit() { cout << "成员函数正在访问" << building->m_SittingRoom << endl; cout << "成员函数正在访问" << building->m_BedRoom << endl; } void GoodFriend::visit2() { cout << "成员函数正在访问" << building->m_SittingRoom << endl; //cout << "友元类正在访问" << building->m_BedRoom << endl; // 无法访问 } int main() { GoodFriend gf; gf.visit(); }
原文:https://www.cnblogs.com/baicang/p/15134898.html