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

2024-09-28 19:01:43 发布

您现在位置:Python中文网/ 问答频道 /正文

{}做什么?在试图用Python重写C++程序时发现了这一点,但甚至无法理解该方法的功能。它不是从代码中的任何地方调用的,但它是由程序调用的,并且不能真正理解这是怎么回事?这样的东西什么时候由程序本身调用

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中是否有类似的东西


Tags: 程序lockforintstdsecondsdeviceschrono
1条回答
网友
1楼 · 发布于 2024-09-28 19:01:43

它是一个不接受任何参数且没有返回值的函子。将第一个()视为运算符的名称,第二个()表示参数

例如,如果Foo有这样一个操作符,并且fooFoo的实例,那么

foo();

将调用void operator()()

如果您想将foo的构造与其调用分开,那么它很有用。在很多方面,这是C++中lambda函数的先导,特别是在完全可以在函数范围内声明和定义类型的情况下。p>

相关问题 更多 >