tor=(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()"<? ? }
? ? virtual void print(ostream& out)const
? ? {
? ? ? ? T::print(out);
? ? ? ? out<<", race is "<? ? }
private:
? ? char *race;
? ? int champion;
};
int _tmain(int argc, _TCHAR* argv[])
{
? ? cout<
? ? U u("Moon", 21, "Night Elf", 0);
? ? U t("Grubby", 21, "Orc", 2);
? ? u = t;
? ? cout<
? ? 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;
}
注意setValue函数改变了t2对象的value值,而line26赋值后,t2仍然可以调用setValue函数,这说明“返回const并不意味着类T本身为const,而只意味着你不能使用返回的引用来直接修改它指向的结构”。看看下面这段代码:
int main()
{
? ? T t1;
? ? T t2;
? ? (t2=t1).setValue(21);
? ? return 0;
}
这里直接对t2=t1的返回结果调用setValue,因为返回的是const&类型,所以不能调用此setValue函数。