【发布时间】:2017-09-22 13:50:14
【问题描述】:
我在一个类中重载了前缀和后缀递增/递减运算符。
#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?