How can a derived C++ class clone itself via a base pointer?

后端 未结 6 703
旧巷少年郎
旧巷少年郎 2021-01-13 09:34

Here\'s what I\'m trying to do (this code doesn\'t work):

class Base
{
    virtual Base *clone() { return new Base(this); }
    virtual void ID() { printf(\"         


        
6条回答
  •  隐瞒了意图╮
    2021-01-13 10:26

    With Base bp = &d;

    You've "sliced" d, so to the compiler, bp really is only of type Base, which is why when you call bp->clone() the compiler calls Base::clone(); and bp2->ID() prints BASE.

    Base& bp = d; will do what you want.

提交回复
热议问题