我有以下代码:
#include <cstdio>
#include <iostream>
using namespace std;
class A
{
int a, b;
public:
A() : A(5, 7) {}
A(int i, int j)
{
a = i;
b = j;
}
A operator+(int x)
{
A temp;
temp.a = a + x;
temp.b = b + x;
return temp;
}
~A() { cout << a << " " << b << endl; }
};
int main()
{
A a1(10, 20), a2;
a2 = a1 + 50;
}
输出结果如下:
60 70
60 70
10 20
代码几乎按预期工作。问题是它会打印对象
a2
的值两次...这意味着析构函数被调用了两次...但为什么会被调用两次呢?
temp
也是一个对象。 - Oliver Charleswortha1+50
创建的临时对象无法省略。 - T.C.