類模板的模板友元函式定義

2022-08-29 23:27:20 字數 1899 閱讀 8737

類模板的模板友元函式定義有2種方式:

1. 將友元模板函式直接定義在類模板中。這種方式比較簡單直接。

2. 將友元模板函式宣告在類模板中,定義在類模板之外。這種方式的寫法,如果不小心,通常會出現編譯沒問題,鏈結時無法解析的錯誤。

以下是乙個簡單的正確的例子:

1 #include 2 #include 3

4 template 5

class

number; 6

7 template 8

void print(const number&n); 9

10 template 11 std::ostream& operator

<< (std::ostream& os, const number&n);

1213 template 14 std::istream& operator>>(std::istream& is, number&n);

1516 template 17

void printvector(const std::vector& vt, const number&n);

1819 template 20

class

number

24 ~number() {}

2526

private:27

t val;

28public

:29 friend void print(const number&n);

30 friend std::ostream& operator

<< (std::ostream& os, const number&n);

31 friend std::istream& operator>> (std::istream& is, number&n);

3233 friend number& operator += (number& a, const number&b)

3438 template 39 friend void printvector(const std::vector& vt, const number&n);

40 template 41

void memfunc(const std::vector& vt, const number&n);

42};

4344 template 45 std::ostream& operator

<<(std::ostream& os, const number&n)

4650

51 template 52 std::istream& operator >>(std::istream& is, number&n)

5357

58 template 59

void print(const number&n)

6063

64 template 65

void printvector(const std::vector& vt, const number&n)

6671

72 template 73 template 74

void number::memfunc(const std::vector& vt, const number&n)

7580

1) 以上**中,operator +=被定義在類模板內部。其他3個函式先被宣告(需提前宣告類模板,如果模板函式的引數中含有類模板),然後在類模板中被宣告為友元函式, 之後被定義在類模板體之外。

2) 請注意當模板函式被宣告為類模板的友元時,在函式名之後必須緊跟模板實參表,用來代表該友元宣告指向函式模板的例項。否則友元函式會被解釋為乙個非模板函式,鏈結時無法解析。

3) 友元模板函式的模板引數型別,並不一定要求是類模板的引數型別,也可以另外宣告。

模板類的 友元模板函式

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...

模板類的 友元模板函式

模板類的 友元模板函式 第二名 12 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 te...

模板類中如何定義友元函式?

今天看到乙個演算法題,就是如果有兩個大整數求和,但是這兩個大整數的取值範圍超過了計算機能表示的範圍,要怎麼辦?正好之前看了線性表的順序儲存結構,覺得可以將大整數的每一位儲存到陣列中,然後對陣列進行對應位的計算!線性表的順序儲存結構的 實現可以看我的前面的部落格,有介紹。現在要寫乙個大整數求和的演算法...