管理每个对象的静态计数器变量



我想为每个创建的对象计算升序和降序数据。但是我不能单独处理它,因为我创建的两个对象也使用相同的静态变量。代码如下,我必须如何进行更改。

void MyObject::handle_receive(std::size_t length) {
getIncrementCount()++;
if(some-condition)
{
getIncrementCount() = 0;
getDecreaseCount() = 0;
}
}
void MyObject::handle_timeout() {
getDecreaseCount()++;
if(some-condition)
{
getIncrementCount() = 0;
getDecreaseCount() = 0;
}
}
int & MyObject::getDecreaseCount()
{
static int theCount = 0;
return theCount;
}
int & MyObject::getIncrementCount()
{
static int theCount = 0;
return theCount;
}
main()
{
for (size_t i = 0; i < SensorSettingsList.size(); i++) {
try {
MyObject *ipPingReporter = new MyObject(io_service, SensorSettingsList.at(i).biosName);
}
catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
}
}

请重新审视static的含义。它与您想要的恰恰相反——它是一个在相同类型的所有对象之间共享的变量。

为了在对象中保持状态,您需要使变量成为类的一部分,而不是函数的一部分:

class MyObject {
int incrementCount;
void increment() {
++incrementCount;
}
int getIncrementCount() {
return incrementCount;
}
};

(为了简洁起见,我在类中实现了这些方法。您可以继续在void MyObject::increment中实现它们,这可以说更好。(

除此之外(与您的问题有些无关(,我建议您不要返回对这些变量的引用。您不希望外部类修改该值。现在,在您的代码中,没有什么可以阻止我通过调用someObject.getIncrementCount() = 15来扰乱计数。

最新更新