1.使用类模板创建数组
下面这段代码:是创建一个元素为 T 类型的数组。
1 #pragma once 2 3 template<class T> 4 class MyArray 5 { 6 public: 7 //有参构造 8 MyArray(int capacity) 9 { 10 mCapacity = capacity; 11 mSize = 0; 12 pAdress = new T[mCapacity]; 13 } 14 //拷贝构造 15 MyArray(const MyArray& my1) 16 { 17 this->mCapacity = my1.mCapacity; 18 this->mSize = my1.mSize; 19 this->pAdress = new T[mCapacity]; 20 for (int i = 0; i < mSize; i++) 21 pAdress[i] = my1.pAdress[i]; 22 } 23 //重载等号操作符 24 MyArray& operator=(const MyArray& my1) 25 { 26 if (this->pAdress != NULL) 27 { 28 delete[] pAdress; 29 this->pAdress = NULL; 30 } 31 this->mCapacity = my1.mCapacity; 32 this->mSize = my1.mSize; 33 this->pAdress = new T[mCapacity]; 34 for (int i = 0; i < mSize; i++) 35 pAdress[i] = my1.pAdress[i]; 36 return *this; 37 } 38 //重载[]号操作符 39 T& operator[](int index) 40 { 41 return this->pAdress[index]; 42 } 43 44 //尾插法 45 void pushBack(T val) 46 { 47 if (mSize == mCapacity) 48 return; 49 pAdress[mSize] = val; 50 mSize++; 51 } 52 //尾部删除法 53 void popBack() 54 { 55 mSize--; 56 } 57 ~MyArray() 58 { 59 if (this->pAdress) 60 { 61 delete[] pAdress; 62 pAdress = NULL; 63 mCapacity = 0; 64 mSize = 0; 65 } 66 } 67 68 69 private: 70 T* pAdress; //指向数组的指针 71 int mCapacity; 72 int mSize; 73 };
2.下面这段代码:是利用上面的模板创建了两个数组(一个是基本数据类型,一个是自定义的类型)
1 //普通类型 2 void test021() 3 { 4 MyArray<char> arr(10); 5 for (char i = ‘a‘; i <= ‘j‘; i++) //给数组赋值 6 arr.pushBack(i); 7 for (int i = 0; i < 10; i++) 8 cout << arr[i]<<" "; 9 }
//自定义的类型 10 class person 11 { 12 public: 13 person() 14 { 15 this->mName = new char[strlen("undefined!") + 1]; 16 strcpy(this->mName, "undefined!"); 17 mAge = -1; 18 } 19 //有参构造 20 person(char *name, int age) 21 { 22 mName = new char[strlen(name) + 1]; 23 strcpy(mName, name); 24 mAge = age; 25 } 26 //拷贝构造 27 person(const person& p1) 28 { 29 mName = new char[strlen(p1.mName) + 1]; 30 strcpy(mName, p1.mName); 31 mAge = p1.mAge; 32 } 33 34 //重载等号操作符 35 person& operator=(const person& p1) 36 { 37 if (mName != NULL) 38 { 39 delete[] mName; 40 mName = NULL; 41 } 42 mName = new char[strlen(p1.mName) + 1]; 43 strcpy(mName, p1.mName); 44 mAge = p1.mAge; 45 return *this; 46 } 47 ~person() 48 { 49 if (mName) 50 { 51 delete[] mName; 52 mName = NULL; 53 } 54 } 55 public: 56 char *mName; 57 int mAge; 58 }; 59 60 61 //自定义类型 62 void test022() 63 { 64 //自定义类型做数组元素时,类型必须提供默认无参构造函数。 65 MyArray<person> arr(10); 66 67 person p1("john1", 19); 68 person p2("john2", 29); 69 person p3("john3", 39); 70 person p4("john4", 49); 71 person p5("john5", 59); 72 73 arr[1] = p1; 74 arr.pushBack(p2); 75 cout << "Name:" << arr[0].mName << " Age:" << arr[0].mAge << endl; 76 arr.pushBack(p3); 77 cout << "Name:" << arr[1].mName << " Age:" << arr[1].mAge << endl; 78 79 }
原文:http://www.cnblogs.com/yyx1-1/p/5731158.html