You need to enable JavaScript to run this app. C++类内如何正确调用重载的operator()运算符?
优惠活动
大模型
产品
解决方案
定价
更多

C++类内如何正确调用重载的operator()运算符?

问题原因与解决方案

错误根因

this是指向当前实例的指针,本身不支持函数调用语法,直接写this(*p++)相当于把指针变量当成函数调用,自然会触发expression cannot be used as a function编译错误。

正确调用方式

有两种常用的正确写法:

  • 写法1:先对this解引用拿到实例对象,再调用重载的operator()
(*this)(*p++);
  • 写法2:在类成员作用域内直接显式调用运算符成员函数
operator()(*p++);

修改后完整可运行代码

#include <iostream>

struct S
{
    void operator()(char c){ std::cout << c << std::endl; };
    void operator()(const char * p)
    {
        while( *p != '\0' )
        {
             (*this)( *p++ ); // 也可替换为 operator()(*p++);
        }
    }
} s ;

int main()
{
    s( "blqhblqh" );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 11:03:04