使用纯虚方法克隆C++类

Joa*_*les 6 c++ virtual

我有以下关系类.我想克隆类Derived,但我得到错误"无法实例化抽象类".我如何克隆派生类?谢谢.

class Base {
public:
    virtual ~Base() {}
    virtual Base* clone() const = 0;
};

class Derived: public Base {
public:
    virtual void func() = 0;
    virtual Derived* clone() const {
        return new Derived(*this);
    }
};
Run Code Online (Sandbox Code Playgroud)

Ser*_* K. 7

只能实例化具体的类.您必须重新设计Derived的接口才能进行克隆.首先,删除virtual void func()= 0; 然后你就可以编写这段代码了:

class Base {
public:
    virtual ~Base() {}
    virtual Base* clone() const = 0;
};

class Derived: public Base {
public:
    virtual Derived* clone() const {
        return new Derived(*this);
    }
};
Run Code Online (Sandbox Code Playgroud)

另一个解决方案是将纯虚函数保留在原位并添加一个具体类:

class Base {
public:
    virtual ~Base() {}
    virtual Base* clone() const = 0;
};

class Derived: public Base {
public:
    virtual void func() = 0;
};

class Derived2: public Derived {
public:
    virtual void func() {};
    virtual Derived2* clone() const {
        return new Derived2(*this);
    }
};
Run Code Online (Sandbox Code Playgroud)


VGE*_*VGE 2

只有具体类可以被实例化。Func 不应该是纯粹的。