友元的功能是让一个函数或者类,能够访问另一个类中的私有成员。
实现方法:
1.全局函数作为友元:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| #include<iostream> using namespace std; #include<string>
class Building{ friend void goodfri(Building *building);
public: Buliding(){ this->m_sittingroom="keting"; this->m_bedroom="woshi"; } public: string m_sittingroom; private: string m_bedroom; };
void goodfri(Building *building){ cout<<"now is:"<<building->m_sittingroom<<endl; cout<<"now is:"<<building->m_bedroom<<endl; }
void test01(){ Building b; goodfri(&b); } int main(){ test01(); return 0; }
|
2.类做友元:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| #include<iostream> using namespace std; #include<string>
class Building; class goodfri{ public: goodfri(); void visit(); private: Building *building; };
class Building{ friend class goodfri; public: Building(); public: string m_sittingroom; private: string m_bedroom; };
Building::Building(){ this->m_sittingroom="keting"; this->m_bedroom="woshi"; }
goodfri::goodfri(){ building=new Building; }
void goodfri::visit(){ cout<<"now in:"<<building->m_bedroom<<endl; cout<<"now in:"<<building->m_sittingroom<<endl; }
void test01(){ goodfri hfri; hfri.visit(); }
int main(){ test01(); system("pause"); return 0; }
|
3.成员函数作为友元:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| #include<iostream> using namespace std; #include<string> class Building; class goodfri{ public: goodfri(); void visit(); void visit2(); private: Building *building; };
class Building{ friend void goodfri::visit();
public: Building(); public: string m_sittingroom; private: string m_bedroom; };
Building::Building(){ this->m_bedroom="woshi"; this->m_sittingroom="keting"; }
goodfri::goodfri(){ building=new Building; } void goodfri::visit(){ cout<<"now is:"<<building->m_sittingroom<<endl; cout<<"now is:"<<building->m_bedroom<<endl; } void goodfri::visit2(){ cout<<"now is:"<<building->m_sittingroom<<endl; } void test01(){ goodfri hhh; hhh.visit(); } int main(){ test01(); system("pause"); return 0; }
|