为什么在这段代码中调用函数调用运算符?

add*_*ssh 1 c++ loops operator-overloading c++11

我不明白为什么该语句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;
}
Run Code Online (Sandbox Code Playgroud)

输出 -

#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;
}
Run Code Online (Sandbox Code Playgroud)

JeJ*_*eJo 5

我不明白为什么该行test()()正在调用函数调用运算符?

这条线上发生了两件事

test()();
^^^^^^   -----> temporary `test` object (1)
      ^^ -----> operator() call         (2)
Run Code Online (Sandbox Code Playgroud)

您正在创建一个临时(右值)test对象(即直到test())并operator()通过第二组调用()

这也相当于说

test().operator()();
Run Code Online (Sandbox Code Playgroud)

或者

test{}.operator()();
Run Code Online (Sandbox Code Playgroud)

或者

test{}();
Run Code Online (Sandbox Code Playgroud)

另请记住,这个临时对象将在行尾被销毁。operator()如果您的意图是致电t,您应该简单地

t();
Run Code Online (Sandbox Code Playgroud)