2019独角兽企业重金招聘Python工程师标准>>>
拷贝构造函数形参类型必须为对象类型
- A( A other ) { } 将导致无穷递归,编译不会出错,但是运行时,会把内存耗尽
- A( const A& other) { } 不会产生内存耗尽
2、赋值构造函数----重载赋值操作符
标准实现如下:
class String
{
private:
char* ptr;
public:
//....
String& String::operator=(const String &str)
{
if(this == &str)
{
return *this;
}
delete []ptr;
ptr = null;
ptr = new[strlen(str.ptr) + 1]; //strlen(字符串)不包括最后的\0,但是sizeof(字符串)包括后面的\0。
strcpy(ptr, str.ptr);
return *this;
}
//.....
}
关注五点:
- 形参--by const reference
- 返回值为引用类型
- 先判断是否是自赋值,不判断的话,会导致删除自身
- 记住delete,防止内存泄漏
- 深拷贝
String& String::operator=(const String &str)
{
if(&str != this)
{
String tempStr(Str);
char* pTemp = tempStr.ptr;
tempStr.ptr = this->ptr;
this->ptr = pTemp;
}
return *this;
}