void operator>>(std::istream& is, String& S1)
{
cout << "Please input length";
is >> S1.len; //主要引起错误原因
cout << "Please input char";
is >> S1.str; //S1.str是一指针变量
}
String::~String()
{
cout << "The number of members is " << --num << endl;
cout << "The adress is " << (int*)str << endl;
delete[] str;
cout << "Have been delete" << endl;
}
先执行代码1,再执行代码2,会报错的信息
表示我错误修改了堆内存,因为我将字符串地址给了S1.str,最后我在析构类该类时,会将字符串内存地址释放,但是我们不能释放系统分配的内存,因此就报错了。
应修改为
void operator>>(std::istream& is, String& S1)
{
cout << "Please input string" << endl;
char* c = new char;
is >> c;
S1.len = strlen(c);
strcpy_s(S1.str, S1.len + 1, c);
}