friend在c 中使用

2021-06-16 04:14:22 字數 2316 閱讀 7522

應用:

pg1.m_vecpt == pg2.m_vecpt (1)

pg1是nestpolygon

類的物件,m_vecpt

是nestpolygon

類的成員變數,

定義如下:

vectorm_vecpt;

因為nestpoint2d

不是內建型別,所以不能直接使用==

等號,所以需要過載==

。class

afx_ext_class nestpoint2d

展開:1、整個類可以是另乙個類的友元,該友元也可以稱做為友類。

class internet;

class country

;這樣internet類中的成員函式可以通過函式引數(也就是country物件或者country物件引用)訪問country類的私有成員。

(理解:country宣告 internet是是它的友元(朋友),那麼 country就信任internet,所以在internet中的成員函式,通過country物件或者country物件引用就能夠訪問internet的私有資料)

迭代器中也有類似的用法:(實質上這個是巢狀友元類的用法,同時這也是一種設計模式)

template

class stacktemplate

//constructor

class iterator;//forward declaration

friend class iterator; //讓iterator類成為stacktemplate的友元類

class iterator //定義乙個類

iterator (stacktemplate& st, bool):s(st),index(s.top){}

t operator*() const

//這裡operator*()訪問了stacktemplate類是私有成員

//過載++,+ 等運算子

}iterator begin()

iterator end()

}使用:

stacktemplateis;

stacktemplate::iterator iterstart = is.begin();

stacktemplate::iterator iterend = is.end();

2、乙個類的成員函式可以是另乙個類的友元

class internet;

class country

;class internet

;通過友元函式的引數internet物件,訪問internet類的私有成員。

(理解:在internet中 申明country的成員函式editurl是internet的友元函式,那麼internet 信任該函式,所以函式country::editurl可以通過internet物件訪問internet的私有成員)

3、乙個普通函式可以是(多個)類的友元函式。這類普通函式的引數都有類的物件,從而通過該物件,操作該類的私有成員,該函式被當作全域性函式。

4、二元中綴運算子,如果第乙個運算數不是類物件,通常把該函式宣告為該類的友元函式。另外:在ostream的過載《或者》符號的時候,通常宣告為友元函式。

5、友元關係既不繼承,也不傳遞

6、友元函式主要缺點是需要額外的**來支援動態繫結

要得到虛友元(virtual

friend

)的效果,友元函式應該呼叫乙個隱藏的(通常是

protected:

)虛成員函式。

class base ;

inline void f(base& b)

class derived : public base ;

void usercode(base& b)

在usercode(base&)中的f(b)語句將呼叫虛擬

的b.do_f()。這意味著如果b實際是乙個派生類的物件,那麼derived::do_f()將獲得控制權。注意派生類覆蓋的是保護的虛(protected:

virtual

)成員函式

do_f()

; 而不是它友元函式f(base&)。

乙個使用虛友元函式用法更實際的例子:(為乙個完整的繼承層次的類提供列印

)class base ;

inline std::ostream& operator<< (std::ostream& o, 

const base& b

)class derived : public base ;

在C 中使用Queue

介紹 queue類執行將放在在queue中的物件採用先進先出的資料結構。物件從一端插入到佇列中從另一端移除。物件的順序程序使用queue queue介面 queue類實現了三個主要集合介面 icollection ienumerable和icloneable。queue的重要方法 queue類常用的...

在 C 中使用畫筆

出處 在 c 中使用畫筆 public class rectangle shape protected point m start protected point m end public rectangle point start,point end,color fgcolor m start s...

在 C 中使用 Python script

想要在c 中嵌入script 除了自己寫指令碼引擎外,lua,python 都可以在c 中使用,另外 monobind,angelscript library 都是一些c script library,可以嵌入到c 中使用 今天在c 中試著嵌入 python 示例 在 python 2.5.2 de...