Eri*_*ric 2 c++ inheritance operator-overloading
为什么这段代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
给出错误:
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&&’
Run Code Online (Sandbox Code Playgroud)
为什么+运营商继承了,但=运营商没有?
类Y包含隐式声明的赋值运算符,它隐藏在基类中声明的运算符.通常,在派生类中声明函数会隐藏在基类中声明的具有相同名称的任何函数.
如果您想同时使用Y,请使用using声明:
class Y : public X {
public:
using X::operator=;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4174 次 |
| 最近记录: |