C++: Inheritance and Operator Overloading

只谈情不闲聊 提交于 2019-12-18 13:16:46

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/3410688/c-inheritance-and-operator-overloading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!