【问题标题】:C++: Inheritance and Operator OverloadingC++:继承和运算符重载
【发布时间】:2010-08-04 23:34:50
【问题描述】:

我有两个结构:

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&amp; rhs)

标签: c++ inheritance operator-overloading


【解决方案1】:

问题在于编译器通常会为你创建一个operator=(除非你提供一个),而这个operator= 隐藏了继承的那个。您可以通过 using-declaration 否决这一点:

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

【讨论】:

  • 不错!我不知道。
猜你喜欢
  • 2012-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多