gpt4 book ai didi

c++ - 临时对象在 C++ 中的行为如何?

转载 作者:行者123 更新时间:2023-11-27 23:38:57 24 4
gpt4 key购买 nike

当我尝试运行下面的代码时,我完全糊涂了..

#include<iostream>
using namespace std;

class test{
public:
int num = 30;

int yourAge ;

void set(){
yourAge = (test().num)*2;
}
};

int main(){
test obj;


cout << test().yourAge << endl; // i was expecting garbage but giving me 0
cout << obj.yourAge << endl; // ya! garbage it is, in this case

///// now/////

test().set()
cout << test().yourAge << endl; // Iwas expecting 60 but giving me againg 0

cout << obj.yourAge << endl; // I was expecting garbage but giving me 0;



return 0;
}

我已经在代码中描述了我的问题,但为什么它们给出了意想不到的结果。为什么会这样?是因为我正在使用临时无名对象还是发生了其他事情?我将感谢您的回答。

最佳答案

在任何使用test() 的地方,您都会构建一个类型为test 的临时对象,该对象会按照您的类中的指定进行初始化。
此初始化对于 num 成员是 30,但对于 yourAge 成员可以是任何东西(静态存储除外,但这是另一个主题)。

然后像 test().yourAge 这样的任何表达式都会构建一个临时对象,检索它的 yourAge 成员,该成员的值是未初始化(它可能是-17、0 或其他)并让这个临时对象消失。

当调用 test().set() 时,您创建一个临时对象,通过 set() 方法初始化其 yourName 成员但是让这个对象消失而不使用它!
任何后续的 test() 表达式都是一个新的临时对象,没有理由与调用 set() 的对象相关。

obj 的情况类似,除了这个对象将持续到包含它的 block (这里的 main() 函数)被执行。
它的 yourAge 成员从未被初始化,所以它可以包含任何东西;如果您曾经使用过 obj.set(),那么在调用之后您可能会期望在 obj.yourAge 中找到相关内容。

关于c++ - 临时对象在 C++ 中的行为如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57106062/

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