修改如下:
#include
using namespace std;
class CStrtemp
{
public:
CStrtemp()
{};
CStrtemp(char *s);
CStrtemp(const CStrtemp &);
~CStrtemp();
CStrtemp Input(CStrtemp *temp);
void show();
void set(char *s);
private:
char *str;
};
CStrtemp::CStrtemp(char *s)
{
cout << "constructor." << endl;
str = new char[strlen(s) + 1];
str = "hello";
if(!str)
{
cerr << "Allocating Error." << endl;
exit(1);
}
strcpy(str, s);
}
CStrtemp::CStrtemp(const CStrtemp &temp)
{
cout << "copy constructor." << endl;
str = new char[strlen(temp.str) + 1];
if(!str)
{
cerr << "error in apply new space.r" << endl;
exit(1);
}
strcpy(str, temp.str);
}
CStrtemp::~CStrtemp()
{
cout << "destructor." << endl;
if(str != NULL)
delete[]str;
}
void CStrtemp::show()
{
cout << str << endl;
}
void CStrtemp::set(char *s)
{
/*你上来就把输入的数组删除了,那么该地址被释放,str就分配不到空间了。因为你的str是根据s来生成的 删除这句 delete[]s; */
str = new char[strlen(s) + 1];
if(!str)
{
cerr << "Allocation Error." << endl;
exit(1);
}
strcpy(str, s);
}
CStrtemp CStrtemp::Input(CStrtemp *temp)
{
char *s;
s = new char[strlen(temp ->str) + 1];
cout << "Please input the string:" << endl;
cin >> s;
temp ->set(s);
return *temp;
}
int main()
{
CStrtemp C;
CStrtemp *A = &C;
A ->set("class A set string");//加一句,因为你调用的是空构造函数,所以你show之前不设置的话,str指针是空的。这时你调用show会报错,
A ->show();
CStrtemp B = A ->Input(A);
A ->show();
B.show();
return 0;
}
结果如下图:
错误提示是什么?
修改后:
#include
using namespace std;
class CStrtemp
{
public:
CStrtemp();
CStrtemp(char *s);
CStrtemp(const CStrtemp &);
~CStrtemp();
CStrtemp Input(CStrtemp *temp);
void show();
void set(char *s);
private:
char *str;
};
CStrtemp::CStrtemp()
{
cout << "constructor." << endl;
str = new char[strlen("hello") + 1];
str = "hello";
if(!str){
cerr << "Allocating Error." << endl;
exit(1);
}
}
CStrtemp::CStrtemp(char *s)
{
cout << "constructor." << endl;
str = new char[strlen(s) + 1];
//str = "hello";
if(!str){
cerr << "Allocating Error." << endl;
exit(1);
}
strcpy(str, s);
}
CStrtemp::CStrtemp(const CStrtemp &temp){
cout << "copy constructor." << endl;
str = new char[strlen(temp.str) + 1];
if(!str){
cerr << "error in apply new space.r" << endl;
exit(1);
}
strcpy(str, temp.str);
}
CStrtemp::~CStrtemp(){
cout << "destructor." << endl;
if(str != NULL)
delete[]str;
}
void CStrtemp::show(){
cout << str << endl;
}
void CStrtemp::set(char *s){
// delete[]s;
str = new char[strlen(s) + 1];
if(!str){
cerr << "Allocation Error." << endl;
exit(1);
}
strcpy(str, s);
}
CStrtemp CStrtemp::Input(CStrtemp *temp){
char s[100];
// s = new char[strlen(temp ->str) + 1];
cout << "Please input the string:" << endl;
cin >> s;
temp->set(s);
return *temp;
}
int main(){
CStrtemp C;
CStrtemp *A = &C;
A->show();
CStrtemp B = A->Input(A);
A->show();
B.show();
return 0;
}