C++用拷贝构造函数来改错,急!!!

来源:百度知道 编辑:UC知道 时间:2024/09/24 00:34:05
#include <iostream.h>
#include <string.h>
class NAME {
public: NAME()
{ string = NULL;
cout << "Constructing.\n";
}
~NAME()
{ cout << "Destructing.\n";
if (string != NULL) delete []string;
}
void show() { cout << string << "\n"; }
void set(char* s)
{ if (string!=NULL) delete []string;
string = new char[strlen(s) + 1];
if (string!=NULL) strcpy(string, s);
}
private:
char* string;
};

NAME get_name()
{ NAME temp_obj;//①
char temp_str[250]; //②
cout << "Input your name: ";
cin >> temp_str;
temp_obj.set(temp_str); //③
return temp_obj; //④
} //⑤

void main()
{ NAME myname;
myname = get_name();
myname.show();
}

//-----------以上是出错了的代码-----------------------------------

#include <iostream.h>
#include <string.h>
class NAME {
public: NAME()
{ string = NULL;
cout << "Constructing.\n";
}
~NAME()
{ cout << "Destructing.\n";
if (string != NULL) delete []string;
}
void show() { cout << string << "\n"; }
void set(char* s)
{ if (string!=NULL) delete []string;
string = new char[strlen(s) + 1];
if (string!=NULL) strcpy(string, s);
}
NAME &operator=(const NAME &a)
{
if(string!=NULL)
delete []string;
string =new char[strlen(a.string)+1];
strcpy(string,a.string);
return *this;
}
private:
char* string;
};

NAME& get_name(NAME &temp_obj)
{ //①
char temp_str[250]; //②
cout << "Input your name: ";
cin >> temp_str;
temp_obj.set(temp_str