作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我有以下代码:
#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
的值两次......这意味着析构函数被调用了两次......但为什么它被调用了两次?
最佳答案
在赋值a2=a1+50
时,分配了一个包含a1+50
的临时对象。
此对象在复制到a2
后立即销毁。
关于c++ - 为什么析构函数被调用两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26315191/
我是一名优秀的程序员,十分优秀!