沒有友元之前,一個(gè)類是不能直接訪問其它類的private成員的 引進(jìn)友元機(jī)制是允許一個(gè)類的private,protected成員的訪問權(quán)授予給指定的其它函數(shù)和其它類 2.定義 定義友元的關(guān)鍵字friend 格式: class classname{ ... friend functionname();//聲明類的友元函數(shù) friend class othername();//聲明類的友元類 }; functionname(){} //定義友元函數(shù)代碼細(xì)節(jié) class othername(){}; //定義友元友元類代碼細(xì)節(jié) 2.1.在類中定義友元函數(shù) 代碼舉例 //friend1.cpp pass with vc++6.0 or dev-c++4.9 #include <iostream> class x{ public: x():a(11),b(33){}//構(gòu)造函數(shù)初始化列表 friend void x_friend_f(x&); friend class use_x; private: int a; int b; }; void x_friend_f(x& xx)//x的友元函數(shù)實(shí)現(xiàn) {std::cout<<"a,b in class x is: "<<xx.a<<","<<xx.b<<std::endl;}
int main(){ x demo; x_friend_f(demo); return 0; } .在類中定義友元類 class screen{ public: ... friend class window_msg;//在類中聲明一個(gè)友元window_msg類 priavte: int height; int width; int index; }; //在另一類window_msg中直接訪問screen類的private成員 class window_msg{ public: ... }; //友元類可以直接訪問 window_msg& window_msg::relocate(screen::index r,screen::index c,screen& s) { s.height +=r; s.width +=c; return *this; } 3.基類與派生類 友元關(guān)系不能被繼承,基類的友元對(duì)派生類的成員沒有任何訪問權(quán)限 也就是說如果基類有友類函數(shù)和友元類,它們能訪問基類任何成員,而不能訪問由這個(gè)基類繼承的派生類的任何成員 4.設(shè)計(jì)指導(dǎo) 類的友元函數(shù)又叫做類的非成員函數(shù) 1.何時(shí)使用類的成員函數(shù) 當(dāng)我們對(duì)類自身對(duì)象進(jìn)行操作時(shí),操作如賦值=,下標(biāo)(),調(diào)用(),自增++,自減-- 操作的返回結(jié)果也在類的自身對(duì)象,就直接選擇用成員方法實(shí)現(xiàn) 2.何時(shí)使用類的非成員函數(shù)即友元函數(shù) 當(dāng)我們對(duì)類的兩個(gè)以上對(duì)象進(jìn)行操作時(shí),如關(guān)系運(yùn)算,輸入>>,輸出<<,請(qǐng)選用友元函數(shù)
|