2011-12-13 107 views
0

我有一個數據結構,它接受c'tor中的抽象類。我想將該類(通過克隆方法)複製到其中一個數據結構的專用字段中,因此我不必將其保存在結構之外。 我已經找到jsmith的這種解釋對cplusplus.com從抽象基類中派生類的調用c'tor

// 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抽象?

回答

3

你需要重寫

Derived* clone() const; 

注意const

+0

哇我很高興從複製源代碼時犯了同樣的錯誤! – itchy23