【发布时间】:2019-11-28 01:42:04
【问题描述】:
当我尝试运行下面的代码时,我完全糊涂了..
#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().set()然后期望test().yourAge以某种方式更改是错误的,因为在每种情况下,都会在表达式结束时创建和销毁新的临时对象。除了静态变量的情况外,不同的临时变量之间没有任何联系。