今天突然想到一个问题:C++中多态该如何完成赋值呢?形如以下的情况:
class Base
{
public:
Base() : a(0){}
Base(int n) : a(n){}
~Base(){}
//使用缺省的operator =
//...
private:
int a;
};
class Derived : public Base
{
public:
Derived() : Base(), b(0){}
Derived(int ia, int ib) : Base(ia), b(ib){}
~Derived(){}
//使用缺省的operator =
//...
private:
int b;
};
现在定义两个指向Derived对象的Base指针:
Base *pb = new Derived(1, 1);
Base *an_pb = new Derived();
问题来了,用户可能会做出以下的操作:
*an_pb = *pb;
当用户做这样的操作时所期望的行为是把pb所指向的Derived对象的成员依次赋给an_pb所指向的对象的各成员,但他真正得到的行为却只有Base的operator =被调用了。显然缺省的operator = 无法完成需要,而virtual operator = 也是不可能的。这时我们引入一个额外的virtual member function:
virtual Base& Base::clone(const Base& b)
{
a = b.a;
return *this;
}
virtual Derived& Derived::clone(const Base& d)
{
Base::clone(d);
b = dynamic_cast<const Derived&>(d).b;
return *this;
}
再定义Base和Derived的operator = 来调用clone函数便可以解决问题了:
Base& operator =(const Base& b)
{
this->clone(b);
return *this;
}
Derived& operator =(const Derived& d)
{
this->clone(d);
return *this;
}
问题得到了解决!!!
2741

被折叠的 条评论
为什么被折叠?



