简体   繁体   English

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

[英]C++: Inheritance and Operator Overloading

I have two structs: 我有两个结构:

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;
    } 
};

I would like the following to compile: 我想要以下编译:

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

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

Is there any way to make this work, or must I define the operator in Ftw as well? 有没有办法让这项工作,或者我必须在Ftw定义运算符?

The problem is that the compiler usually creates an operator= for you (unless you provide one), and this operator= hides the inherited one. 问题是编译器通常会为您创建一个operator= (除非您提供一个),并且此operator=隐藏继承的operator= You can overrule this by using-declaration: 您可以通过using声明来否决它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM