在程序里,有些所有属性也想让类外特殊的一些函数进行访问,就需要用到友元技术。友元的目的就是让一个函数或类访问另一个类中私有成员。友元的关键字就是friend.
友元的三种实现:
简单实例 全局变量做友元:
#include <iostream> #include <string> using namespace std;class Building { friend void goodgay (Building* b) ; string bedroom; public : Building () { livingroom = "客厅" ; bedroom = "卧室" ; } string livingroom; };
void goodgay (Building* b) { cout << "好基友正在访问......" << b->livingroom << endl; cout << "好基友正在访问......" << b->bedroom << endl; } void test01 () { Building b; goodgay (&b); }
int main () { test01 (); return 0 ; }
好基友正在访问......客厅 好基友正在访问......卧室
类做友元:
#include <iostream> #include <string> using namespace std;class Building { friend class Goodgay ; string bedroom; public : Building (); string livingroom; }; class Goodgay { public : Building* b; void visit () ; Goodgay (); };
Building::Building () { livingroom = "客厅" ; bedroom = "卧室" ; } void Goodgay::visit () { cout << "好基友正在访问......" << b->livingroom << endl; cout << "好基友正在访问......" << b->bedroom << endl; } Goodgay::Goodgay () { b = new Building; } void test01 () { Goodgay gg; gg.visit (); }
int main () { test01 (); return 0 ; }
好基友正在访问......客厅 好基友正在访问......卧室
成员函数做友元:
#include <iostream> #include <string> using namespace std;class Building { friend void Goodgay::visit () ; private : string bedroom; public : Building (); string livingroom; }; class Goodgay { public : Building* b; void visit () ; Goodgay (); ~Goodgay (); };
Building::Building () { livingroom = "客厅" ; bedroom = "卧室" ; } void Goodgay::visit () { cout << "好基友正在访问......" << b->livingroom << endl; cout << "好基友正在访问......" << b->bedroom << endl; } Goodgay::Goodgay () { b = new Building; } Goodgay::~Goodgay () { delete b; b = nullptr ; } void test01 () { Goodgay gg; gg.visit (); }
int main () { test01 (); return 0 ; }
好基友正在访问......客厅 好基友正在访问......卧室
课本实例 友元函数: #include <iostream> #include <string> using namespace std;class Croster { friend bool Equal (Croster&, Croster&) ; string name; int Math; const double Score; double GPA; public : Croster (string na = "undef" , int m = 100 , double s = 3 ); double GetGPA () const ; };
#include "l4_08.h" Croster::Croster (string na, int m, double s) :name (na), Math (m), Score (s) { GPA = Math / 100.0 * Score; } double Croster::GetGPA () const { return GPA; } bool Equal (Croster &A, Croster &B) { if (A.GPA==B.GPA) return true ; else return false ; }
#include "l4_08.h" int main () { Croster stuA ("李梅" , 96 , 3 ) , stuB ("孙立" , 98 , 3 ) ; if (Equal (stuA, stuB)) cout << "GPA is same\n" ; else cout << "GPA is different\n" ; return 0 ; }
其他的大同小异,就不赘述了…………..