gpt4 book ai didi

c++ - 为什么是2020年的产量?

转载 作者:行者123 更新时间:2023-12-04 11:54:00 24 4
gpt4 key购买 nike

我有以下代码:

#include <iostream>
using namespace std;

class Foo {
int data;
public:
Foo(int d = 0) {
data = d;
}

~Foo() {
cout << data;
}
};

int main() {
Foo a;
a = 20;
return 0;
}
这段代码的输出是2020。我想会发生什么,创建了一个临时对象a。一旦使用赋值运算符将值赋值为 20,就会调用析构函数并打印 20。然后 main 函数到达 return 并且第二次调用析构函数,再次打印 20。
我对吗?

最佳答案

你是对的。
实际修改你的代码如下,可以更清楚地展示代码的逻辑。

#include <iostream>
using namespace std;

class Foo {
int data;
public:
Foo(int d = 0) {
cout << "call constructor!" << endl;
data = d;
}

~Foo() {
cout << data << endl;
}
};

int main() {
Foo a; // Foo::Foo(int d = 0) is called which yields the first line of output
a = 20; // is equal to follows

// 1. a temporary object is constructed which yields the second line of output
Foo tmp(20);
// 2. since you do not provide operator= member function,
// the default one is generated the compiler
// and a member-wise copy is performed
a.operator=(&tmp);
// after this copy assignment, a.data == 20
// 3. tmp is destroyed which yields the third line of output
tmp.~Foo();
// 4. right before the program exits, a is destroyed which yields the last line of output
a.~Foo();

return 0;
}
输出是:

call constructor!

call constructor!

20

20

关于c++ - 为什么是2020年的产量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67154695/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com