友元概念就不羅嗦了,使用也簡單,就兩種形式:
1.友元函式:friend ret-type classname::funname(....);
2.友元類:friend class classname;
唯一要注意的就是不管是友元函式還是友元類,定義友元關係前必須先宣告
友元類其實還是有些故事要說的,一旦類繼承起來友元關係還是有些小複雜的,下面簡單說明:
c中宣告a是其友元類,那麼最基本的就是a可以使用c中的private方法或者物件。
圖中可見,a是b的基類,c是d的基類。abcd中就有如下關係:
1.b新增的方法不能訪問c的私有成員
2.b從a繼承而來的方法可以訪問c的私有成員
3.a只能訪問d中從c中繼承而來的私有成員,d中新增的私有成員不能訪問!
總結起來:
(1)友元關係不可以繼承,但對已有的方法來說訪問許可權不改變。
(2)如果改寫基類的方法則訪問許可權改變
(3)友元關係不具有傳遞性
若類b是類a的友元,類c是b的友元,類c不一定是類a的友元
下面乙個例子說明了友元模板類的定義。
#include
using namespace std;
//using std::cout;
template
class node
;template
class listnode
~listnode();
listnode & insert(int k,t &x);
listnode & delete(t &x);
bool isempty()const;
int length()const;
void display()const;
};template
listnode::~listnode()
}template
bool listnode::isempty()const
template
listnode& listnode::insert(int k,t &x)
else
return *this;
template
int listnode::length()const
return index;
}template
listnode& listnode::delete(t &x)
else
}prev = curr;
curr = curr->next;
}return *this;
}template
void listnode::display()const
}
類模板的模板友元函式定義
類模板的模板友元函式定義有2種方式 1.將友元模板函式直接定義在類模板中。這種方式比較簡單直接。2.將友元模板函式宣告在類模板中,定義在類模板之外。這種方式的寫法,如果不小心,通常會出現編譯沒問題,鏈結時無法解析的錯誤。以下是乙個簡單的正確的例子 1 include 2 include 3 4 te...
模板類中如何定義友元函式?
今天看到乙個演算法題,就是如果有兩個大整數求和,但是這兩個大整數的取值範圍超過了計算機能表示的範圍,要怎麼辦?正好之前看了線性表的順序儲存結構,覺得可以將大整數的每一位儲存到陣列中,然後對陣列進行對應位的計算!線性表的順序儲存結構的 實現可以看我的前面的部落格,有介紹。現在要寫乙個大整數求和的演算法...
模板類的 友元模板函式
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 include include usingnamespacestd template classt c...