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

标签 c++ inheritance operator-overloading

我有两个结构:

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=(除非你提供),而这个operator=隐藏了继承的。您可以通过使用声明否决它:

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

关于C++:继承和运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3410688/

相关文章:

C++ 将 void 指针转换为模板类

c++ 公共(public)继承的类成员不能用作默认参数

java - 传递相同类型的类的参数有什么意义?

delphi - 从专门的泛型类型派生

C++:自动生成(默认)复制构造函数

c++ - '->' and '。'用于对对象的引用?

c++ - 如何断言应该使用 C++11 来编译我的程序?

c++ - OS X IPC 在 C 中获取进程 ID

python 运算符重载 __radd__ 和 __add__

c++ - 调用 operator== 时,MSVC 不会执行用户定义的到 std::nullptr_t 的隐式转换