如何在"this"上调用运算符()?

How do I call operator() on "this"?

本文关键字:运算符 调用 this      更新时间:2023-10-16

我有一个成员函数,它需要在类实例(this(上调用operator((,我猜不到正确的语法。我试过

this();
*this();
this->();
this->operator();

还有一些其他的事情,但错误信息不是很丰富,所以我不知道我做错了什么。

我在SE上找到的最接近的问题是:如何调用模板化运算符((?

(*this)(/*parameters*/)

可能是最清晰的方式。

答案:使用

this->operator()();

我提出了一个例子(测试方法(:

#include <iostream>
class A
{
public:
int operator()(int index)
{
return index + 1;
}
int test()
{
// call to operator ()
return this->operator()(5);
}
};
int main()
{
A obj;
std::cout << obj.test() << std::endl;
std::cout << obj(7) << std::endl;
std::cout << obj.operator()(9) << std::endl;
}