在封裝中C++類數(shù)據(jù)成員大多情況是private屬性;但是如果接口采用多參數(shù)實(shí)現(xiàn)肯定影響程序效率;然而這時(shí)候如果外界需要頻繁訪問(wèn)這些私有成員,就不得不需要一個(gè)既安全又理想的“后門”——友元關(guān)系; C++中提供三種友元關(guān)系的實(shí)現(xiàn)方式,友元函數(shù)、友元成員函數(shù)、友元類。 友元函數(shù):既將一個(gè)普通的函數(shù)在一個(gè)類中說(shuō)明為一個(gè)friend屬性;其定義(大多數(shù)會(huì)訪問(wèn)該類的成員)應(yīng)在類后; 友元成員函數(shù):既然是成員函數(shù),那么肯定這個(gè)函數(shù)屬于某個(gè)類,對(duì)了就是因?yàn)檫@個(gè)函數(shù)是另外一個(gè)類的成員函數(shù),有時(shí)候因?yàn)槲覀兿胗靡粋€(gè)類通過(guò)一個(gè)接口去訪問(wèn)另外一個(gè)類的信息,然而這個(gè)信息只能是被它授權(quán)的類才能訪問(wèn);那么也需要用friend去實(shí)現(xiàn);這個(gè)概念只是在聲明的時(shí)候稍有變化; 友元類:友元類聲明會(huì)將整個(gè)類說(shuō)明成為另一個(gè)類的友元關(guān)系;和之前兩種的區(qū)別是集體和個(gè)人的區(qū)別;友元類的所有成員函數(shù)都可以是另一個(gè)類的友元函數(shù); 值得注意的是友元關(guān)系是單向的,有點(diǎn)像我們戀愛(ài)中出現(xiàn)的單相思 O(∩_∩)O,單向關(guān)系就是說(shuō)如果A被說(shuō)明成B的友元關(guān)系,那么只能說(shuō)A是B的友元,并不代表B是A的友元;其次在多數(shù)情況下友元關(guān)系的函數(shù)都會(huì)訪問(wèn)它被說(shuō)明中類的成員,這時(shí)候應(yīng)該將函數(shù)定義在類的后面; 下面給一個(gè)簡(jiǎn)單的例程代碼;
1 #include <iostream> 2 3 using namespace std; 4 5 class B; 6 7 class A{ 8 private: 9 int x; 10 public: 11 A(); 12 void display(B &); 13 }; 14 15 class C; 16 17 class B{ 18 private: 19 int y; 20 int z; 21 public: 22 B(); 23 B(int, int); 24 friend void A::display(B &);//友元成員函數(shù) 25 friend void display(B &);//友元函數(shù) 26 friend class C;//友元類 27 }; 28 29 class C{ 30 private: 31 int sum; 32 void calc(B &); 33 public: 34 C(); 35 void display(B &); 36 }; 37 38 //必須在友元關(guān)系的類后進(jìn)行定義 39 void display(B &v)//友元函數(shù) 40 { 41 cout << v.y << " " << v.z << endl; 42 } 43 44 A::A() 45 { 46 this->x = 0; 47 } 48 49 void A::display(B &v)//友元成員函數(shù) 50 { 51 this->x = v.y + v.z; 52 cout << this->x << endl; 53 } 54 55 B::B() 56 { 57 this->y = 0; 58 this->z = 0; 59 } 60 61 B::B(int y, int z) 62 { 63 this->y = y; 64 this->z = z; 65 } 66 67 C::C() 68 { 69 sum = 0; 70 } 71 72 void C::display(B &v) 73 { 74 this->calc(v); 75 cout << sum << " = " << v.y << " + " << v.z << endl; 76 } 77 78 void C::calc(B &v) 79 { 80 sum = v.y + v.z; 81 } 82 83 int main() 84 { 85 A a; 86 B b(2, 3); 87 display(b); 88 a.display(b); 89 C c; 90 c.display(b); 91 92 return 0; 93 } 94 |
|