Trouble with inheritance of operator= in C++

前端 未结 5 1560
灰色年华
灰色年华 2020-11-27 04:20

I\'m having trouble with the inheritance of operator=. Why doesn\'t this code work, and what is the best way to fix it?

#include 

class A
{
         


        
5条回答
  •  野性不改
    2020-11-27 05:09

    What's happening is that the default operator = that the compiler generates for any class that doesn't have one is hiding the base class' operator =. In this particular case, the compiler is generating const B &B::operator =(const B &) for you behind the scenes. Your assignment matches this operator and completely ignores the one you declared in class A. Since a C& cannot be converted to a B& the compiler generates the error you see.

    You want this to happen, even though it seems vexing right now. It prevents code like you've written from working. You don't want code like that to work because it allows unrelated types (B and C have a common ancestor, but the only important relationships in inheritance are parent->child->grandchild relationships, not sibling relationships) to be assigned to one another.

    Think about it from an ISA perspective. Should a Car be allowed to be assigned to a Boat just because they're both Vehicles?

    In order make something like this work you should use the Envelope/Letter pattern. The envelope (aka handle) is a specialized class who's only job it is is to hold an instance of some class that's derived from a particular base class (the letter). The handle forwards all operations but assignment to the contained object. For assignment it simply replaces the instance of the internal object with a copy-constructed (using a 'clone' method (aka virtual constructor)) copy of the assigned from object.

提交回复
热议问题