2014-01-12 24 views
0

我試圖在我的一些類中支持複製函數,並且爲此我創建了一個基類(一個接口)。但除了那個類,我還有另一個繼承它的類,它需要重寫「copy」函數並提供一個新的返回類型。我複製類的方法是使用包裝類自動刪除指向新分配的對象的指針,當它不再使用時。它是一個模板類,不符合協變類型。我剛纔描述長得像這樣:將虛擬函數從基類轉發到具有相同簽名的另一個虛函數

template <T> 
struct BASE { 
    virtual PTR<BASE> copy() const = 0; 
}; 

template <Y> 
struct DERIVED : public BASE<Y> { 
    virtual PTR<DERIVED> copy() const = 0; // ERROR: PTR<DERIVED> not a covarient type to PTR<BASE>. 
}; 

知道這是不合法的C++,我在想,如果我可以做類似這樣的這樣的東西:

template <T> 
struct DERIVED : public BASE<T> { 
    virtual PTR<DERIVED> DERIVED::copy() const = 0; // Derived classes should override this function and act as if "PTR<BASE<T>> BASE<T>::copy() const" does not exist. 

    private: // hide function so that "PTR<DERIVED>" function is called, but when dealing with the base class call the following function. 
    PTR<BASE<T>> BASE<T>::copy() const { 
     return PTR<BASE<T>>((BASE<T>*)DERIVED::copy()->GetAndRelease()); // Convert the "PTR<DERIVED>" object to a "PTR<BASE<T>>" object. 
    } 
}; 

上面的代碼不會編譯,因爲在類中定義類時不能命名該類。 EX:在類中定義一個函數時,不能做「DERIVED :: copy」,至少在我這樣做時,G ++會給我一個錯誤。值得一提的是,提到的「PTR」類的工作原理是這樣的:

template <T> 
struct PTR { 
    PTR(T* ptr); // set the pointer to the data; 
    ~PTR(); // destroy the object pointed to by "ptr"; 

    T* get(); // get the pointer to the data; 
    T* GetAndRelease(); // just to simplify the example, this function returns the pointer and makes it so that the class does not delete the pointer when it is deconstructed. 

    private: 
    T* ptr; 
} 

回答

0

你不能重載基於返回類型。簡單的解決方法是使copy()功能virtual接口,而是有它只是調用virtual接口:

(我

不做虛函數公衆的成語標準庫使用相當一致認爲例外是std::exception::what())。它還方便地側重隱藏其他過載的覆蓋問題(例如,參見std::num_put<...>put()do_put()成員)。

相關問題