其他分享
首页 > 其他分享> > c-为什么重载的赋值运算符不被继承?

c-为什么重载的赋值运算符不被继承?

作者:互联网

这个问题已经在这里有了答案:            >            Trouble with inheritance of operator= in C++                                    5个
>            operator= and functions that are not inherited in C++?                                    3个
为什么这样的代码:

class X {
public:
    X& operator=(int p) {
        return *this;
    }
    X& operator+(int p) {
        return *this;
    }
};

class Y : public X { };

int main() {
    X x;
    Y y;
    x + 2;
    y + 3;
    x = 2;
    y = 3;
}

给出错误:

prog.cpp: In function ‘int main()’:
prog.cpp:14:9: error: no match for ‘operator=’ in ‘y = 3’
prog.cpp:14:9: note: candidates are:
prog.cpp:8:7: note: Y& Y::operator=(const Y&)
prog.cpp:8:7: note:   no known conversion for argument 1 from ‘int’ to ‘const Y&’
prog.cpp:8:7: note: Y& Y::operator=(Y&&)
prog.cpp:8:7: note:   no known conversion for argument 1 from ‘int’ to ‘Y&&’

为什么继承运算符,而=运算符却不继承?

解决方法:

Y类包含隐式声明的赋值运算符,这些运算符隐藏了在基类中声明的运算符.通常,在派生类中声明一个函数会隐藏任何在基类中声明相同名称的函数.

如果要在Y中都提供它们,请使用using声明:

class Y : public X {
public:
    using X::operator=;
};

标签:c,operator-overloading,inheritance
来源: https://codeday.me/bug/20191011/1892896.html