C 類模板案例 (實現乙個通用的陣列類)

2021-10-19 17:46:28 字數 3115 閱讀 3718

案例描述:實現乙個通用的陣列類,要求如下:

.hpp檔案

#include

#include

using

namespace std;

template

<

class

t>

class

myarray

//拷貝構造

myarray

(const myarray& arr)

}//operator= 過載 防止淺拷貝問題

myarray&

operator=(

const myarray& arr)

//深拷貝

this

->m_capacity = arr.m_capacity;

this

->m_size = arr.m_size;

this

->paddress =

new t[arr.m_capacity]

;//拷貝資料

for(

int i =

0; i <

this

->m_size; i++

)return

*this;}

//尾插法

void

push_back

(const t& val)

this

->paddress[

this

->m_size]

= val;

this

->m_size++

;//更新陣列大小

}//尾刪法

void

pop_back()

this

->m_size--;}

//過載 通過下標訪問元素

t&operator

(int index)

//返回陣列的容量

intgetcapacity()

//返回陣列的大小

intgetsize()

//析構函式

~myarray()

}private

: t* paddress;

//指標指向堆區開闢的真實陣列

int m_capacity;

//陣列容量

int m_size;

//陣列大小

};

帶測試 總原始碼

#include

#include

using

namespace std;

template

<

class

t>

class

myarray

//拷貝構造

myarray

(const myarray& arr)

}//operator= 過載 防止淺拷貝問題

myarray&

operator=(

const myarray& arr)

//深拷貝

this

->m_capacity = arr.m_capacity;

this

->m_size = arr.m_size;

this

->paddress =

new t[arr.m_capacity]

;//拷貝資料

for(

int i =

0; i <

this

->m_size; i++

)return

*this;}

//尾插法

void

push_back

(const t& val)

this

->paddress[

this

->m_size]

= val;

this

->m_size++

;//更新陣列大小

}//尾刪法

void

pop_back()

this

->m_size--;}

//過載 通過下標訪問元素

t&operator

(int index)

//返回陣列的容量

intgetcapacity()

//返回陣列的大小

intgetsize()

//析構函式

~myarray()

}private

: t* paddress;

//指標指向堆區開闢的真實陣列

int m_capacity;

//陣列容量

int m_size;

//陣列大小 };

void

printintarray

(myarray<

int>

&arr1)

}void

test01()

cout <<

"列印輸出"

<< endl;

printintarray

(arr1)

;//尾刪

arr1.

pop_back()

; cout <<

"容量為: "

<< arr1.

getcapacity()

<< endl;

cout <<

"大小為: "

<< arr1.

getsize()

<< endl;

}//測試自定義資料型別

class

person

person

(string name,

int age)

string m_name;

int m_age;};

//列印函式

void

printpersonarray

(myarray

&arr)

}void

test02()

intmain()

c 模板學習12之通用陣列類模板案例封裝

arr.hpp pragma once include using namespace std 通用的陣列模板類 template class t class myarray 深拷貝構造,防止淺拷貝 myarray const myarray a 賦值運算子過載,防止淺拷貝 a b c鏈式程式設計 ...

陣列類封裝案例C 模板

陣列類封裝案例 實現乙個通用的陣列類,要求如下 可以對內建資料型別以及自定義型別的資料進行儲存 將陣列中的資料儲存到堆區 建構函式中可以傳入陣列的容量 提供對應的拷貝建構函式以及operater 防止淺拷貝問題 提供尾插法和尾刪法對陣列中的資料進行增加和刪除 可以通過下標的方式訪問陣列中的元素 可以...

乙個string類的簡單實現案例

string類中使用到了賦值建構函式 複製建構函式 建構函式 預設建構函式 析構函式 過載操作符等一些類操作 class string string const char str string const char str,int n string const string src 拷貝建構函式 也...