derived class's virtual assignment operator not being called

后端 未结 2 856
忘了有多久
忘了有多久 2021-01-20 07:20

I\'m pretty new to C++, and am trying to come to grips with virtual assignment. The program below consists of an abstract base class with two data members, and a derived cla

2条回答
  •  生来不讨喜
    2021-01-20 07:56

    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(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(hs).style) + 1];
        std::strcpy(style, dynamic_cast(hs).style);
        return *this;
    }
    

提交回复
热议问题