一、在c++中是否能夠將泛型程式設計應用於類?
類模板一些類主要用於儲存和組織資料元素
類中資料組織的方式和資料元素的具體型別無關
如:陣列類,鍊錶類,stack類,queue類
c++中的類模板
以相同的方式處理不同的型別
在類宣告前使用template進行標識
用於說明類中使用的泛指型別t
類模板的應用template
<
typename t>
class
operator
;
只能顯示指定具體型別,無法自動推導
使用具體型別定義物件
宣告的泛指型別t可以出現在類模板的任意地方operator<
int>op1;
operator op2;
int i=op1.op(
1,3)
;string s=op2.op(
"d.t"
,"software"
);
編譯器對類模板的處理方式和函式模板相同
從類模板通過具有型別產生不同的類
在宣告的地方對類模板**本身進行編譯
在使用的地方對引數替換後的**進行編譯
例項分析1:類模板初探
二、類模板的工程應用#include
#include
using
namespace std;
template
<
typename t >
class
operator
t minus
(t a, t b)
t multiply
(t a, t b)
t divide
(t a, t b)};
string operator
-(string& l, string& r)
intmain()
類模板必須在標頭檔案中定義
類模板不能分開實現在不同的檔案中
類模板外部定義的成員函式需要加上模板<>宣告
例項分析2:模板類的工程應用
#ifndef _operator_h_
#define _operator_h_
template
<
typename t >
class
operator
;template
<
typename t >
t operator
::add
(t a, t b)
template
<
typename t >
t operator
::minus
(t a, t b)
template
<
typename t >
t operator
::multiply
(t a, t b)
template
<
typename t >
t operator
::divide
(t a, t b)
#endif
#include
#include
#include
"operator.h"
using
namespace std;
intmain()
第五十八課 類模板的概念和意義
1 類模板 1 一些類主要用於儲存和組織資料 2 類中資料組織的方式 和資料元素的具體型別無關 3 如陣列類 鍊錶類 stack類 queue類等 4 c 將模板的思想應用於類,使得類的實現不關注資料元素的具體型別,而只關注類所需要實現的具體功能 2 c 中的類模板 1 以相同的方式處理不同的型別 ...
五十八課 類模板的概念和意義
上節課我們使用泛型程式設計的思想應用於函式模板,這節課我們就來學習下泛型程式設計的思想是否可以用類上面呢?c 中將模板的思想應用於類,使得類的實現不關注資料元素的具體型別,而之關注類所實現的具體功能。1 c 中的類模板 templateclass operator 2 類模板的應用 operator...
類模板的概念和意義
類模板的概念和意義 類模板一些類主要用於儲存和組織資料元素 類中資料組織的方式和資料元素的具體型別無關 如 陣列類,鍊錶類,stack類,queue類等 c 中將模板的思想應用於類,使得類的實現不關注資料元素的具體型別,而只關注類所需要實現的功能 c 中的類模板 以相同的方式處理不同的型別 在類宣告...