C++:继承和运算符重载

9

我有两个结构体:

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 中定义运算符?

通常 operator = 接受 const 引用参数... 将 T operator=(const T rhs) 改为 T operator=(const T& rhs) 会更好。 - a1ex07
1个回答

22

问题是编译器通常会为你创建一个operator=(除非你提供了一个),而这个operator=会隐藏继承的那个。你可以通过使用声明来覆盖它:

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

不错!我不知道那个。 - Nick Heiner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接