在此,我们为上面的例子,添加复制构造和复制赋值函数
CTest::CTest(const CTest &t)
{
p = new Name[size = t.size];
for (unsigned int i = 0; i < size; i++)
{
p[i] = t.p[i];
}
}
CTest& CTest::operator = (const CTest& t)
{
if (this != &t)
{
delete [] p;
p = new Name[size = t.size];
for ( unsigned int i = 0; i < size; i++)
{
p[i] = t.p[i];
}
}
return *this;
}
在 CTest& CTest::operator= (const CTest& t)
用&this != &t 来防止自赋值
在复制赋值的时候,要先释放自身占用的内存
delete[] p
最后返回 (*this)