C++中复制构造函数与重载赋值操作符总结(二)
{
return this;
}
// Please delete the memory, this maybe cause the memory leak
if (pValue)
{
delete pValue;
}
// Malloc the new memory for the pValue
pValue = new wchar_t[MAXSIZE];
memset(pValue, 0, sizeof(wchar_t) * MAXSIZE);
wcscpy_s(pValue, MAXSIZE, test.pValue);
return this;
}
void Print()
{
wcout<
}
private:
wchar_t *pValue; // The pointer points the memory
};
int main()
{
CTest obj(L"obj");
obj.Print();
CTest obj2(L"obj2");
obj2.Print();
obj2 = obj;
obj2.Print();
obj2 = obj2;
obj2.Print();
return 0;
}
特别是在实现重载赋值构造函数时需要多多的注意,在代码中我也添加了注释,大家可以认真的
阅读一下代码,然后就懂了,如果不懂的就可以留言问我;当然了,如果我哪里理解错了,也希望大家能给我提出,我们共同进步。
复制构造函数的一些细节
1.以下哪些是复制构造函数
X::X(const X&);
X::X(X);
X::X(X&, int a=1);
X::X(X&, int a=1, int b=2);
这些细节问题在这里也说一说,我也是从别人的博客里看到的,这里自己也总结一下。对于一个类X, 如果一个构造函数的第一个参数是下列之一:
a) X&
b) const X&
c) volatile X&
d) const volatile X&
且没有其他参数或其他参数都有默认值,那么这个函数是拷贝构造函数。
X::X(const X&); //是拷贝构造函数
X::X(X&, int=1); //是拷贝构造函数
X::X(X&, int a=1, int b=2); //当然也是拷贝构造函数
2.类中可以存在超过一个拷贝构造函数
class X {
public:
X(const X&); // const 的拷贝构造
X(X&); // 非const的拷贝构造
};
注意,如果一个类中只存在一个参数为 X& 的拷贝构造函数,那么就不能使用const X或volatile X的对象实行拷贝初始化。如果一个类中没有定义拷贝构造函数,那么编译器会自动产生一个默认的拷贝构造函数。这个默认的参数可能为 X::X(const X&)或 X::X(X&),由编译器根据上下文决定选择哪一个。在我的Visual Studio 2012中,当定义了多个复制构造函数以后,编译器就会有warning,但是程序还能正确运行。