#问题:C++拷贝构造中的形参类型和传进来的实参类型必须是同类型吗?
#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)//拷贝构造
{
this->mSize = arr.mSize;
this->mCapacity = arr.mCapacity;
this->pAddr = new T(this->mCapacity);
for (int i = 0; i < this->mSize; i++)
{
this->pAddr[i] = arr.pAddr[i];
}
}
T& operator[](int index)
{
return this->pAddr[index];
}
MyArray<T> operator= (const MyArray<T>& arr)
{
if (this->pAddr)
{
delete[] this->pAddr;
}
this->mSize = arr.mSize;
this->mCapacity = arr.mCapacity;
this->pAddr = new T(this->mCapacity);
for (int i = 0; i < this->mSize; i++)
{
this->pAddr[i] = arr.pAddr[i];
}
return *this;
}
void PushBack(T& data)
{
//判断容器中是否有位置
if (this->mSize >= this->mCapacity)
{
return;
}
this->pAddr[this->mSize] = data;//????想知道这行调用的是拷贝构造还是等号操作符重载还是等号赋值??
this->mSize++;
}
void PushBack(T&& data)
{
//判断容器中是否有位置
if (this->mSize >= this->mCapacity)
{
return;
}
this->pAddr[this->mSize] = data;
this->mSize++;
}
~MyArray()
{
if (this->pAddr)
{
delete[] this->pAddr;
}
}
public:
//一共可以容下多少个元素
int mCapacity;
//当前数组有多少元素
int mSize;
//保存数据的首地址
T* pAddr;
};
void test0401()
{
MyArray<int> marray(20);
int a = 10;
marray.PushBack(a);
marray.PushBack(100);
for (int i = 0; i < marray.mSize; i++)
{
cout << marray[i] << " ";
}
cout << endl;
}
int main04_1(void)
{
test0401();
return 0;
}