我有以下代码:
#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);
}
我期望在
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) {
^
Derived::operator()(int&)
声明隐藏了Base::operator()(int&&)
。
您可以通过在 Derived 类中添加
using Base::operator()
来重新引入隐藏声明。