我有一个数据结构,接受c'tor中的抽象类。我想将类(通过克隆方法)复制到数据结构的私有字段之一,因此我不必将其存储在结构之外。 我在cplusplus.com上通过jsmith找到了这个解释:
// Depending upon your needs, you might not require a base class
// clonable concept. It would only be needed if you need to store
// clonable objects polymorphically.
struct clonable {
virtual ~clonable() {}
virtual clonable* clone() const = 0;
};
class Base : public clonable {
public:
virtual Base* clone() const
{ return new Base( *this ); }
};
class Derived : public Base {
public:
virtual Derived* clone() const
{ return new Derived( *this ); }
};
这是我到目前为止所拥有的:
template <class T>
class AbstractBase {
public:
virtual AbstractBase<T>* clone() const = 0;
virtual int operator()(const T& lhs, const T& rhs) const = 0;
};
template <class T>
class Derived : public AbstractBase<T> {
public:
Derived* clone() { return new Derived(*this); } /* ERROR: can't instantiate abstract class */
int operator()(const T& lhs, const T& rhs) const { return something; }
};
template <class T>
class DataStructure {
public:
DataStructure(AbstractBase<T>* base) : base(base->clone()) {}
//...
private:
AbstractBase<T>* base;
}
我意识到它正在调用AbstractBase
的c'tor。是否有一种优雅和/或简单的方法来解决这个问题,同时保持AbstractBase
抽象?
答案 0 :(得分:3)
您需要覆盖
Derived* clone() const;
请注意const
。