You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何该operator()未被继承?C++重载运算符继承问题咨询

为什么Derived对象调用operator()(10)会编译失败?

代码示例

#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);
}

编译错误信息

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++的名称隐藏(Name Hiding)机制:

  • 当派生类Derived定义了自己的operator()(int&)函数后,基类Base中所有同名的operator()重载都会被自动隐藏。
  • 调用derived(10)时,编译器只会在Derived的作用域内查找operator(),找到的唯一候选是需要左值引用的operator()(int&),而10是右值,无法绑定到左值引用,因此编译报错。
  • 名称隐藏规则会阻止编译器自动去基类中查找其他重载版本,哪怕基类存在匹配的右值引用重载。

解决方法

在Derived类的public区域添加using Base::operator();,将基类的所有operator()重载引入到派生类的作用域中,这样编译器就能匹配到基类的右值引用版本:

class Derived : public Base {
  public:
    using Base::operator(); // 引入基类的operator()重载
    void operator()(int &x) {
        std::cout << x << '\n';
    }
};

内容的提问来源于stack exchange,提问作者schuelermine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 01:38:18