2010-08-04 83 views
9

我有两个结构:C++:继承和运算符重载

template <typename T> 
struct Odp 
{ 
    T m_t; 

    T operator=(const T rhs) 
    { 
     return m_t = rhs; 
    } 
}; 

struct Ftw : public Odp<int> 
{ 
    bool operator==(const Ftw& rhs) 
    { 
     return m_t == rhs.m_t; 
    } 
}; 

我想下面的编译:

int main() 
{ 
    Odp<int> odp; 
    odp = 2; 

    Ftw f; 
    f = 2; // C2679: no operator could be found 
} 

有什么办法,使这项工作,或者我必须定义运营商在Ftw以及?

+0

通常'运营商='需要const引用参数......这将是更好的改变'T运算符=(const的牛逼右)''到T接线员=(常量:您可以通过使用声明否决此T&rhs)' – a1ex07 2010-08-04 23:47:39

回答

22

问题是编译器通常为你创建一个operator=(除非你提供一个),并且这个operator=隐藏了继承的。

struct Ftw : public Odp<int> 
{ 
    using Odp<int>::operator=; 
    bool operator==(const Ftw& rhs) 
    { 
     return m_t == rhs.m_t; 
    } 
}; 
+0

不错!我不知道那件事。 – 2010-08-05 00:06:49