我正在尝试跟踪给定类创建了多少对象。如果我在类中重载运算符 ++ ,则会调用析构函数,但我不知道为什么。更具体:
class num{
public:
virtual void setValue(int)=0;
static int db;
num(){}
~num(){}
};
int num::db = 0;
class int32: public num{
public:
// GET
int getValue();
// SET
void setValue(int f);
// constructor
int32()
{
cout << "Construction..."<<endl;
this->value = 0;num::db++;
}
// destructor
~int32()
{
cout << "destruction..."<<endl;
num::db--;
}
// operators
int32 operator++(int);
int32 operator++(void);
protected:
int value;
};
int32 int32::operator ++()
{
this->value++;
return *this;
}
int32 int32::operator ++(int)
{
this->value++;
return *this;
}
int main()
{
int32 i;
i.setValue(20);
cout << (i++).getValue()<<endl;
cout << (++i).getValue()<<endl;
cout << num::db;
cout << endl << "End of execution.";
return 1;
}
结果是:构造... 21 破坏... 22 破坏... -1 End of execution.destruction...
所以在 ++i 和 i++ 之后调用了一个析构函数,但是为什么呢?
非常感谢!