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
关键字并不认识重载或如何调用它,请查看此页面上的运算符和重载。 - Uselessoperator()
。Python中类似的方法称为__call__
。 - molbdnilo