为什么重载的赋值运算符不能继承? [英] Why does an overloaded assignment operator not get inherited?

查看:306
本文介绍了为什么重载的赋值运算符不能继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这段代码:

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&&’

为什么 + 运算符继承,但 = 运算符不是?

Why is the + operator inherited, but the = operator not?

推荐答案

Y 包含隐式声明的赋值运算符,它隐藏在基类中声明的运算符。通常,在派生类中声明函数会隐藏在基类中声明的具有相同名称的任何函数。

Class Y contains implicitly-declared assignment operators, which hide the operator declared in the base class. In general, declaring a function in a derived class hides any function with the same name declared in a base class.

如果要在<$ c $中同时使用它们c> Y ,使用using声明:

If you want to make both available in Y, use a using-declaration:

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

这篇关于为什么重载的赋值运算符不能继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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