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

后端 未结 6 757
旧巷少年郎
旧巷少年郎 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:17

    Your example is incorrect and will not compile. Specifically this line:

    Base bp = &d;
    

    That may also be the root cause of your problem (you may be slicing your object), but I can't tell for certain without seeing working code.

    You also have a problem where your two classes are not related (did you mean to write class Derived : public Base?)

提交回复
热议问题