2013-04-23 31 views
1

我有這個基類(詳細信息刪除)重載基類賦值運算符會導致不明確的分配錯誤

template<class T> 
class GPtr 
{ 
public: 
    typedef T BaseType; 

    GPtr& operator=(const BaseType& rhs) 
    { 
     m_p = rhs.get(); 
     return *this; 
    } 
private: 
    BaseType m_p; 
}; 

然後一個子類專業的模板,並增加了另一項任務選項:

class GDrawablePtr : public GPtr<XYZ> 
{ 
public: 
    GDrawablePtr& operator=(const RootType& rhs) 
    { 
     GPtr::operator =(convert<BaseType::element_type>(rhs)); 
     return *this; 
    } 
/* -- only compiles if this is uncommented 
    GDrawablePtr& operator=(const BaseType& rhs) 
    { 
     GPtr::operator =(rhs); 
     return *this; 
    } 
*/ 
}; 

將該代碼註釋掉後,在分配實例時出現有關模糊賦值的編譯錯誤。如果我取消註釋,那麼即使它看起來沒有做任何新的事情,編譯也是成功的。

有沒有辦法避免重新定義原始的基賦值操作符,以及這種行爲的原因是什麼?

回答

5

它被稱爲隱藏:在派生類中聲明一個函數使基類中具有相同名稱的任何函數都不可訪問。您可以使用使用聲明來使基類版本也可用:

// In GDrawablePtr 
using GPtr::operator=;