我在类中重载了前缀和后缀增加/减少运算符。指向过载前缀和后缀运算符的类对象
#include <iostream>
using namespace std;
class X
{
public:
X() { cout << "X" << endl;}
~X() { cout << "~X" << endl; }
X& operator++() { X *x = new X; return *x; }
X operator++(int) { X *x = new X; return *x; }
X& operator--() { X *x = new X; return *x; }
X operator--(int) { X *x = new X; return *x; }
};
int main()
{
X p;
cout << endl;
++p;
cout << endl;
p++;
cout << endl;
return 0;
}
输出是:
X
X
X
~X
~X
看来,使用后缀增量时,对象被实例化和删除的,但使用前缀时,增加它没有被删除。
这种行为的原因是什么?
你为什么在这里使用'new'? –