derived class's virtual assignment operator not being called

◇◆丶佛笑我妖孽 提交于 2019-12-01 22:19:24

C++ doesn't let you override virtual functions with covariant parameter types. Your derived operator doesn't override the Abstract assignment operator at all, it defines a totally orthogonal operator related only in that it's the same operator name.

You have to be careful creating such functions because if the two actual derived types don't agree, almost certainly the assignment will be nonsensical. I would reconsider whether your design need could be served better by an alternate approach.

This is a bit old, but in case anyone else stumbles upon it:

To add to Mark's answer, you can do this by implementing

Derived & operator=(const Abstract & rs);

In this case you may need to use rs by casting it: dynamic_cast<const Derived &>(rs)
Of course this should only be done carefully. The full implementation would be:

Derived & Derived::operator=(const Abstract & hs)
{
    if (this == &hs)
        return *this;
    Abstract::operator=(hs);
    style = new char[std::strlen(dynamic_cast<const Derived &>(hs).style) + 1];
    std::strcpy(style, dynamic_cast<const Derived &>(hs).style);
    return *this;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!