昨天一个小学弟写c++程序是出现了一个问题后来经过我们和一个大三的学长讨论解决了这个问题感觉不错,拿出分享他报错这个错
代码如下:`#include
using namespace std;
class Point{
public:
Point();
Point(int x,int y,char * str){
this->x=x;
this->y=y;
//this->str=new char[10];
//strcpy(this->str,”Goods”);
this->str=str;
}
Point(int x,int y){
this->x=x;
this->y=y;
str=new char[10];
strcpy(str,"Goods");
}
//深拷贝
Point(const Point & point){
x=point.x;
y=point.y;
str=new char[10];
strcpy(str,point.str);
}
~Point(){
delete [] str;
}
void show();
private:
int x;
int y;
char * str;
};
void Point::show(){
}
int main(){
Point p(3,4);
p.show();
char * str=new char[10];
str=”Goods”;
Point p1(5,6,str);
p1.show();
return 0;
}`
原因出现在这里析构函数中的delete[] 数组 只能删除动态分配的空间,然而我们传入的是保存在文字常量区 的指针,注意虽然main中的str初始化时是指向动态分配的空间但是 str=”Goods”;又变成指向文字常量区 了