提问人:schuelermine 提问时间:10/19/2023 最后编辑:schuelermine 更新时间:10/19/2023 访问量:47
为什么这个运算符没有被继承?[复制]
Why does this operator not get inherited? [duplicate]
问:
我有以下代码:
#include <iostream>
class Base {
public:
virtual void operator()(int &x) = 0;
void operator()(int &&x) {
operator()(x);
}
};
class Derived : public Base {
public:
void operator()(int &x) {
std::cout << x << '\n';
}
};
int main() {
Derived derived;
derived(10);
}
我希望对 on 的调用将尝试调用重载(因为继承是 ),它将调用(因为表达式是右值),它将调用对绑定到 的变量的引用。为什么这不会发生?operator()
Derived
Base::operator()
public
void Base::operator()(int &&x)
void Base::operator()(int &x)
x
10
具体而言,错误消息是:
Documents/fubar.cc:20:5: error: no matching function for call to object of type 'Derived'
derived(10);
^~~~~~~
Documents/fubar.cc:13:10: note: candidate function not viable: expects an l-value for 1st argument
void operator()(int &x) {
^
答:
3赞
Krzysiek Karbowiak
10/19/2023
#1
该声明隐藏了 .Derived::operator()(int&)
Base::operator()(int&&)
可以通过添加 Derived 类来重新引入隐藏的声明。using Base::operator()
评论