C ++:继承和运算符重载 [英] C++: Inheritance and Operator Overloading

查看:217
本文介绍了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 中定义运算符?

Is there any way to make this work, or must I define the operator in Ftw as well?

推荐答案

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

The problem is that the compiler usually creates an operator= for you (unless you provide one), and this operator= hides the inherited one. You can overrule this by using-declaration:

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

这篇关于C ++:继承和运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆