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

为何代码中test()()语句会调用函数调用运算符?

为什么test()()会调用函数调用运算符?

先看你的代码和输出:

#include <iostream>
#include <thread>
using namespace std;

class test{
public:
    test(){
        cout<<"i am in constructor"<<endl;
    }
    void operator() (){
        cout<<"i am in an overloaded function"<<endl;
    }
};

int main()
{
   test t;
   test()();
   return 0;
}

输出:

i am in constructor
i am in constructor
i am in an overloaded function

test()()其实是两步操作的合并,拆开来理解就一目了然:

  • 第一个test():创建一个临时的test类对象,和test t;的逻辑完全一致,会触发类的构造函数,对应输出里的第二行构造信息。
  • 第二个():对刚创建的临时对象,调用你重载的operator()(函数调用运算符),就像你对命名对象t执行t()一样,所以会触发第三行的输出。

换句话说,test()()等价于:

test temp; // 构造临时对象
temp();    // 调用重载的函数调用运算符

只是把这两行代码合并成了一行,直接用临时对象调用运算符。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 16:42:18