STL3-MyArray动态数组类模板实现
生活随笔
收集整理的這篇文章主要介紹了
STL3-MyArray动态数组类模板实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
注意
1、右值的拷貝使用
2、拷貝構造函數的使用?
#include<iostream> using namespace std;template<class T> class MyArray{ public:MyArray(int capacity){this->mCapacity = capacity;this->mSize = 0;//申請內存this->pAddr = new T[this->mCapacity];}//拷貝構造MyArray(const MyArray<T>& arr); T& operator[](int index);MyArray<T> operator=(const MyArray<T>& arr);void PushBack(T& data);//&&對右值取引用void PushBack(T&& data);~MyArray() {if (this->pAddr != NULL){delete[] this->pAddr;}} public:int mCapacity; //數組容量int mSize; //當前數組有多少元素T* pAddr; //保存數組的首地址 }; template<class T> MyArray<T>::MyArray(const MyArray<T>& arr) {//我的 將原有數組拷貝到當前數組 錯誤/*arr->mCapacity = this->mCapacity;arr->mSize = this->mSize;arr->pAddr = new T[this->mCapacity];for (int i = 0; i < mSize; i++){arr->pAddr[i] = this->pAddr[i];}*///將arr拷貝到當前數組this->mCapacity = arr.mCapacity;this->mSize = arr.mSize;//申請內存空間this->pAddr = new T[this->mCapacity];//數據拷貝for (int i = 0; i < this->mSize; i++){this->pAddr[i]=arr.pAddr[i];} } template<class T> T& MyArray<T>::operator[](int index) {return this->pAddr[index]; }template<class T> MyArray<T> MyArray<T>::operator=(const MyArray<T>& arr) {//釋放以前空間if (this->pAddr != NULL){delete[] this - < pAddr;}this->mCapacity = arr.mCapacity;this->mSize = arr.mSize;//申請內存空間this->pAddr = new T[this->mCapacity];//數據拷貝for (int i = 0; i < this->mSize; i++){this->pAddr[i] = arr->pAddr[i];}return *this; }template<class T> void MyArray<T>::PushBack(T& data) {//判斷容器中是否有位置if (this->mSize >= this->mCapacity){return;}//調用拷貝構造 =號操作符//1、對象元素必須能夠被拷貝//2、容器都是值寓意,而非引用寓意 向容器中放入元素都是放入元素的拷貝份//3、如果元素的成員有指針,注意 深拷貝和淺拷貝//深拷貝 拷貝指針 和指針指向的內存空間//淺拷貝 光拷貝指針this->pAddr[this->mSize] = data;mSize++; } #if 1 template<class T> void MyArray<T>::PushBack(T&& data) {//判斷容器中是否有位置if (this->mSize >= this->mCapacity){return;}this->pAddr[this->mSize] = data;mSize++; } #endifvoid test01() {MyArray<int> marray(20);int a = 10,b=20,c=30,d=40;marray.PushBack(a);marray.PushBack(b);marray.PushBack(c);marray.PushBack(d);//錯誤原因:不能對右值取引用//左值 可以在多行使用//右值 只能在當前行使用 一般為臨時變量//增加void PushBack(T&& data)即可不報錯marray.PushBack(100);marray.PushBack(200);marray.PushBack(300);for (int i = 0; i < marray.mSize; i++){cout << marray.pAddr[i] << " ";}cout << endl;MyArray<int> marray1(marray); //拷貝構造函數使用cout << "myarray1:" << endl;for (int i = 0; i < marray1.mSize; i++){cout << marray1.pAddr[i] << " ";}cout << endl;MyArray<int> marray2=marray; //=操作符的使用cout << "myarray2:" << endl;for (int i = 0; i < marray2.mSize; i++){cout << marray2.pAddr[i] << " ";}cout << endl;} class Person{}; void test02() {Person p1, p2;MyArray<Person> arr(10);arr.PushBack(p1);arr.PushBack(p2);}int main() {test01();system("pause");return 0; }運行結果:
?
總結
以上是生活随笔為你收集整理的STL3-MyArray动态数组类模板实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 服务器测试网址填写注意事项
- 下一篇: 数据结构-栈4-栈的应用-中缀转后缀