本文介绍了使用纯虚方法克隆C ++类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下类关系.我想克隆派生类,但出现错误无法实例化抽象类".如何克隆派生类?谢谢.
I have the following relation of classes. I want to clone the class Derived, but I get the error "cannot instantiate abstract class". How I can clone the derived class? Thanks.
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);
}
};
推荐答案
只能实例化具体的类.您必须重新设计Derived的接口才能进行克隆.首先,删除 virtual void func()= 0; 之后,您将可以编写以下代码:
Only concrete classes can be instantiated. You have to redesign the interface of Derived in order to do cloning. At first, remove virtual void func() = 0; Then you will be able to write this code:
class Base {
public:
virtual ~Base() {}
virtual Base* clone() const = 0;
};
class Derived: public Base {
public:
virtual Derived* clone() const {
return new Derived(*this);
}
};
另一种解决方案是将纯虚函数保留在原处,并添加一个具体的类:
Another solution is keeping pure virtual function in-place and adding a concrete class:
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);
}
};
这篇关于使用纯虚方法克隆C ++类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!