C++ 中的 ()() 运算符是什么?

3

void operator()()是什么?在尝试将C++程序转换为Python时找到了这个,但是无法理解此方法的功能。虽然代码中没有从任何地方调用它,但程序还是会调用它,我无法真正理解这是关于什么的。什么情况下程序会自行调用这样的东西?

class MoistureSensor {
    const std::chrono::seconds sleepTime;
    std::mutex& mtx;
    std::set<WaterDevice*> devices;

    const int min = 0;
    const int max = 10;
    const int threshold = 3;

public:
    MoistureSensor(const std::chrono::seconds sleepTime, std::mutex& mtx)
        : sleepTime{ sleepTime }
        , mtx{ mtx }
    {
    }

    void subscribe(WaterDevice& device) {
        devices.insert(&device);
    }

    void operator()(){
        for (;;) {
            std::cout << "this\n";
            std::unique_lock<std::mutex> lock(mtx);

            if (isAirTooDry())
                for (auto p : devices)
                    p->sprinkleWater();
            if (isSoilTooDry())
                for (auto p : devices)
                    p->pourWater();

            lock.unlock();
            std::this_thread::sleep_for(sleepTime);
        }
    }
    void foo();
private:
    bool isAirTooDry();
    bool isSoilTooDry();
    int getAirMoisture();
    int getSoilMoisture();
};

Python中是否有类似于这样的东西?


请提供更多上下文,说明您具体在哪里找到了这个陈述。这将有助于其他研究相同主题的人。 - πάντα ῥεῖ
通常,如果您看到 operator 关键字并不认识重载或如何调用它,请查看此页面上的运算符和重载 - Useless
可以被重载的“函数调用”伪运算符的函数名是operator()。Python中类似的方法称为__call__ - molbdnilo
1个回答

5

这是一个不带任何参数且没有返回值的函数对象。将第一个()看作运算符名称,第二个()表示参数。

例如,如果Foo有这样一个运算符,并且fooFoo的实例,则

foo();

将调用void operator()()函数。

如果你想把foo的构造与调用分开,这个函数非常实用。在很多方面,这预示了C++中的lambda函数,特别是因为你可以在函数的作用域内完全声明和定义一个类型。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接