class T
{
public:
T(const char *pname, int nage)
{
name = new char[strlen(pname)+1];
strcpy_s(name, strlen(pname)+1, pname);
age = nage;
}
T(const T &rhs)
{
name = new char[strlen(rhs.name)+1];
strcpy_s(name, strlen(rhs.name)+1, rhs.name);
age = rhs.age;
}
T& operator=(const T& rhs)
{
if(this != &rhs)
{
cout<<"T&operator="<<endl;
this->~T();
new(this)T(rhs);
}
return *this;
}
virtual ~T()
{
if(name!=NULL)
delete[] name;
cout<<"~T()"<<endl;
}
virtual void print(ostream& out)const
{
out<<"name is "<<name<<", age is "<<age;
}
private:
char *name;
int age;
};
ostream& operator<<(ostream& out, const T&t)
{
t.print(out);
return out;
}
class U:public T
{
public:
U(const char *pname, int nage, const char *prace, int nchampion):T(pname, nage)
{
race = new char[strlen(prace)+1];
strcpy_s(race, strlen(prace)+1, prace);
champion = nchampion;
}
U(const U &rhs):T(rhs)
{
race = new char[strlen(rhs.race)+1];
strcpy_s(race, strlen(rhs.race)+1, rhs.race);
champion = rhs.champion;
}
U& operator=(const U& rhs)
{
if(this != &rhs)
{
/* T::operator=(rhs);
race = new char[strlen(rhs.race)+1];
strcpy_s(race, strlen(rhs.race)+1, rhs.race);
champion = rhs.champion;
*/
this->~U();
new(this)U(rhs);
}
return *this;
}
virtual ~U()
{
if(race!=NULL)
delete[] race;
cout<<"~U()"<<endl;
}
virtual void print(ostream& out)const
{
T::print(out);
out<<", race is "<<race<<", champion number is "<<champion<<".";
}
private:
char *race;
int champion;
};
int _tmain(int argc, _TCHAR* argv[])
{
cout<<sizeof(T)<<" "<<sizeof(U)<<endl;
U u("Moon", 21, "Night Elf", 0);
U t("Grubby", 21, "Orc", 2);
u = t;
cout<<u<<endl;
return 0;
}
在重载operator=运算符时,另一个值得关注的是,用const来修饰返回值:
class T
{
public:
T(int x=12):value(x){}
const T& operator=(const T & rhs)
{
if(this != &rhs)
{
//implement
}
return *this;
}
int getValue()
{
return value;
}
void setValue(int x)
{
value = x;
}
public:
int value;
};
int main()
{
T t1;
T t2;
t2 = t1;
t2.setValue(21);
return 0;
}