C++中级-friend关键字访问类中private
全局函数做友元
#if 0 #include <iostream> #include <string> using namespace std; //用friend关键字访问类中private的函数方法。 class Building { //2.在此用friend关键字声明! friend void SeePrivate(Building* b); public: Building() { Mainroom = "客厅"; Bedroom = "卧室"; } public: string Mainroom; private: string Bedroom; }; //1.通过全局函数做友元访问Private数据 void SeePrivate(Building* b) { cout << b->Bedroom << endl; }; int main() { Building b; //3.只能访问public中的Mainroom。不能访问private中的Bedroom。 cout << b.Mainroom << endl; //cout << b.Bedroom << endl; SeePrivate(&b); return 0; } #endif // 0
类做友元
#if 0 #include <iostream> #include <string> using namespace std; //用friend关键字访问类中private的函数方法。 class Building { //2.在此用friend关键字声明! friend void SeePrivate(Building* b); public: Building() { Mainroom = "客厅"; Bedroom = "卧室"; } public: string Mainroom; private: string Bedroom; }; //1.通过全局函数做友元访问Private数据 void SeePrivate(Building* b) { cout << b->Bedroom << endl; }; int main() { Building b; //3.只能访问public中的Mainroom。不能访问private中的Bedroom。 cout << b.Mainroom << endl; //cout << b.Bedroom << endl; SeePrivate(&b); return 0; } #endif // 0
成员函数做友元
#include <iostream> #include <string> using namespace std; class Building {
//3.声明此函数; friend void Friends::SeeBuilding(); public: Building() { Mainroom = "客厅"; Bedroom = "卧室"; }; public: string Mainroom; private: string Bedroom; }; class Friends { public: //1.创建一个要访问的类的指针对象 Building* bud; //2.在堆区创建一个Building对象 Friends(){bud = new Building;}; void SeeBuilding(){ cout << bud->Mainroom << endl; //4.虽然编译器报错,但是能访问Building类中的pravite数据了、 cout << bud->Bedroom << endl; }; }; int main() { Friends f; f.SeeBuilding(); return 0; }