【发布时间】:2013-06-26 06:04:53
【问题描述】:
可能还有其他例子,但这是我刚刚遇到的。
#include <iostream>
using namespace std;
class Student
{
public:
int x;
};
int main()
{
Student rts;
Student* heap = new Student;
cout << rts.x << endl; // prints out random integer
cout << heap->x << endl; // prints out 0
}
这背后有什么好的理由或逻辑可以理解吗?
【问题讨论】:
-
原因是你没有初始化你的变量,所以允许出现任何随机值。
-
@andre 不是这样。对于 rts 对象,是的,但对于所有堆对象,我得到零。
-
它被称为“未定义的行为”,它甚至可以在你的鼻子里产生恶魔。
-
@KacyRaye 我知道它是零,但这可能只是运气和不同编译器或操作系统的变化。
标签: c++ object runtime heap-memory instance-variables