#include <iostream>
#include <cstring>
using namespace std;
class User {
public:
User (const char* pszName, int nAge) {
m_pszName = new char[strlen(pszName) + 1];
strcpy (m_pszName, pszName);
m_nAge = nAge;
}
User (const User& user) {
cout << "Here is copy constructor" << endl;
m_pszName = new char[strlen(user.m_pszName) + 1];
strcpy (m_pszName, user.m_pszName);
m_nAge = user.m_nAge;
}
User& operator= (const User& user) {
cout << "Here is copy assignment" << endl;
if (&user != this) {
if (m_pszName) {
//delete[] m_pszName;\\为什么去掉也没有错误?
//m_pszName = NULL;
}
m_pszName = new char[strlen(user.m_pszName) + 1];
strcpy (m_pszName, user.m_pszName);
m_nAge = user.m_nAge;
}
return *this;
}
~User (void) {
delete[] m_pszName;
}
void print (void) {
cout << "My name is " << m_pszName << ". I'm " << m_nAge << " years old." << endl;
}
private:
char* m_pszName;
int m_nAge;
};
int main ()
{
User user1 ("Zaphod", 42);
User user2 ("Tom", 38);
user2 = user1;//程序为何没出现错误?
user2.print ();
}
慕容森
浮云间