为什么这个运算符不能被继承?

问题描述 投票:0回答:1

我有以下代码:

#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) {
         ^
c++ inheritance operator-overloading
1个回答
0
投票

Derived::operator()(int&)
声明隐藏了
Base::operator()(int&&)

您可以通过在 Derived 类中添加

using Base::operator()
来重新引入隐藏声明。

© www.soinside.com 2019 - 2024. All rights reserved.