在下面的示例中,我做了deepcopy,但每個東西都可以正常工作,但是當obj2超出範圍,析構函數正在調用並且它在析構函數內部崩潰時,請幫助我的代碼出現問題:深層複製不起作用
#include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
#include <iostream>
#include <conio.h>
using namespace std;
class ClassA
{
private:
char *str;
int id;
public :
ClassA(int x, char *s)
{
int len = strlen(s)+1;
str = new char[len];
id = x;
strcpy(str, s);
}
~ClassA()
{
delete [] str;
}
ClassA(ClassA &obj)
{
id = obj.id;
int len = strlen(obj.str);
str = new char[len] + 1;
strcpy(str, obj.str + 1);
}
void disply()
{
cout << id << " " << str << endl;
}
};
int main()
{
ClassA Obj1(5, "hello");
{
ClassA Obj2 = Obj1;
Obj2.disply();
}
Obj1.disply();
return 0;
}