如何在关键字 this 上调用重载 () 运算符?

Yas*_*med 2 c++ oop overloading

以下内容有效,但当我执行该(*this)(5)部分时感觉很丑。

struct MyStruct
{
    void operator()(int a)
    {
        // Do something with "a"
    }

    void myFunc()
    {
        (*this)(5);
    }
};
Run Code Online (Sandbox Code Playgroud)

我需要重载该()运算符并在其他类方法中使用它。

bol*_*lov 10

您有几个选择:

  • (*this)(5)

  • this->operator()(5)

  • 要不就operator()(5)

  • 创建一个从 中调用的方法operator(),例如:

    void do_work(int a) { /* ... */ }
    void operator()(int a) { do_work(a); }
    void myFunc() { do_work(5); }
    
    Run Code Online (Sandbox Code Playgroud)

无论您选择哪一个都只是个人品味问题。


只是为了好玩,这里还有一些(荒谬的)选项:

  • 我个人的投票是第四个选项。使用命名函数以获得更好的自记录代码。 (2认同)