60 陣列類模板

2021-08-19 21:26:00 字數 1941 閱讀 5218

模板引數可以是數值型引數(非型別引數)

template

void func()

t a[n];   //使用模板引數定義區域性陣列

func();

數值型模板引數的限制:變數不能作為模板引數,浮點數(計算機內部表示不精確)不能作為模板引數,類物件不能作為模板引數。

本質:模板引數是在編譯階段被處理的單元,因此,在編譯階段必須準確無誤的唯一缺點。

最高效的方法求1+2+3+..+n的和?

#include

#include

using namespace std;

template

< typename t, int n >

void func()

;    

for(int i=0; i

class sum

;template

< >                      //完全特化

class sum < 1 >

;//static 靜態成員,具有類變數屬性,使得整個類可以使用,儲存在全域性儲存區,const表示進入符號表,執行之前就能確定他的值

int main()

//int a=10;

// func();   //出錯

cout << "1 + 2 + 3 + ... + 10 = " << sum<10>::value << endl;

cout << "1 + 2 + 3 + ... + 100 = " << sum<100>::value << endl;

//n=10,呼叫x,在呼叫sum<9>...sum<1>,值為1,編譯器做相應計算,在編譯期就能確定結果值,執行時直接列印值。

return 0;

#ifndef _array_h_

#define _array_h_

template

< typename t, int n >

class array

return ret;

template

< typename t, int n >

bool array::get(int index, t& value)

return ret;

template

< typename t, int n >

t& array::operator (int index)

#endif

第34課intarray 擴充套件:

#ifndef _heaparray_h_     //heap   堆上分配空間

#define _heaparray_h_

template

< typename t >

class heaparray

return ret;

template

< typename t >

int heaparray::length()

return ret;

template

< typename t >

bool heaparray::set(int index, t value)

return ret;

template

< typename t >

t& heaparray::operator (int index)

#endif

#include

#include

#include "array.h"

#include "heaparray.h"

using namespace std;

int main()

for(int i=0; i}delete pai;

return 0;

}模板引數可以是數值型引數,數值型模板引數必須在編譯期間唯一確定,陣列類模板是基於數值型模板引數實現的,陣列類模板是簡易的線性表資料結構。

第60課 陣列類模板

1.1 模板引數可以是 數值型引數 非型別引數 template void func 函式呼叫時 func 1.2 數值型模板引數的限制 1.2.1 變數 不能作為模板引數 使用模板時 1.2.2 浮點數 不能作為模板引數 定義模板和使用模板時 1.2.3 類物件 不能作為模板引數 使用模板時 1....

陣列類模板

問題及描述 檔名稱 test.cpp 作者 邱凱 完成日期 2016年5月31號 版本號 v6.0 問題描述 陣列類模板 輸入描述 輸入資料 輸出描述 輸出答案 include include include using namespace std template class array temp...

陣列類模板

檔名稱 3.cpp 完成日期 2016年 6 月 15日 版本號 v1.0 專案 陣列類模板 在陣列類的基礎上,將之改造為類模板,以使陣列中可以儲存各種型別的資料。template 陣列類模板定義 class array include includeusing namespace std temp...