复制构造函数和赋值操作符,为了复制一个对象。书上的代码,不知错在哪,求解
是为了解决复制一个对象 以及用一个对象初始化另一个对象,而复制构造函数 和赋值操作符
这是书上的例子,我前前后后对比了一下 和书上没什么区别。书上能得出正确结果 我的确运行时奔溃。
#include <iostream>#include <string>using namespace std;class MyClass{public: MyClass(int *p); MyClass(const MyClass &rhs); ~MyClass(); MyClass &operator=(const MyClass &rhs);private: int *ptr;};MyClass::MyClass(int *p){ cout<<"Entering regular constructor of object "<<this<<"\n"; ptr = p; cout<<"Leaving regular constructor of object "<<this<<endl;}MyClass::MyClass(const MyClass &rhs){ cout<<"Entering copy constructor of object "<<this<<endl; cout<<"rhs is object "<<&rhs<<endl; *this = rhs; cout<<"Leaving copy constructor of object "<<this<<endl;}MyClass::~MyClass(){ cout<<"Entering destructor of object "<<this<<endl; delete ptr; cout<<"Leaving destructor of object "<<this<<endl;}MyClass &MyClass::operator=(const MyClass &rhs){ cout<<"Entering assignment operator of object "<<this<<endl; cout<<"rhs is object "<<&rhs<<endl; if(this != &rhs) { cout<<"deleteing this->ptr\n"; delete ptr;//具体是在这奔溃的 cout<<"alocate a new int and assign value of *rhs.ptr\n"; ptr = new int; *ptr = *rhs.ptr; } else { cout<<"this and rhs are the same object,we're doing nothing!\n"; } cout<<"Leaving assignment operator of object "<<this<<endl; return *this;}int main(){ cout<<"11111111111111111111111111111111111111111111111111111\n"; {//代码段1 MyClass obj1(new int(1)); MyClass obj2(new int(2)); obj2 = obj1; } cout<<"222222222222222222222222222222222222222222222222222222\n"; {代码段2 MyClass obj3(new int(3)); MyClass obj4=obj3;//运行到这里就奔溃,但是把代码段1注释掉就没问题 } cout<<"3333333333333333333333333333333333333333333333333333333\n"; {//代码段3 MyClass obj5(new int(1)); obj5 = obj5; } return 0;}MyClass::MyClass(const MyClass &rhs): ptr(NULL){ cout<<"Entering copy constructor of object "<<this<<endl; cout<<"rhs is object "<<&rhs<<endl; *this = rhs; cout<<"Leaving copy constructor of object "<<this<<endl;}MyClass &MyClass::operator=(const MyClass &rhs){ cout<<"Entering assignment operator of object "<<this<<endl; cout<<"rhs is object "<<&rhs<<endl; if(this != &rhs) { cout<<"deleteing this->ptr\n"; if (ptr) { delete ptr;//具体是在这奔溃的 } cout<<"alocate a new int and assign value of *rhs.ptr\n"; ptr = new int; *ptr = *rhs.ptr; } else { cout<<"this and rhs are the same object,we're doing nothing!\n"; } cout<<"Leaving assignment operator of object "<<this<<endl; return *this;}
[解决办法]
MyClass obj4你看你这个对象吧。
------解决方案--------------------
obj4没有对应的构造函数啊。
[解决办法]
主要问题是楼主把拷贝构造函数的重任下放给了赋值操作符(=)了。在对象未被构造成功前,你使用了赋值,而且你还delete其中指针的内容,所以出错了。1楼给出了一个方法。我建议楼主还是认认真真的完成拷贝构造函数,而不是把重任下放给赋值操作符。
MyClass::MyClass(const MyClass &rhs){ cout<<"Entering copy constructor of object "<<this<<endl; cout<<"rhs is object "<<&rhs<<endl; ptr = new int; *ptr = *rhs.ptr; cout<<"Leaving copy constructor of object "<<this<<endl;}
[解决办法]
obj4 里面的 ptr没被初始化,你就直接去delete肯定会挂的。
[解决办法]