可能还有其他例子,但这是我刚刚遇到的例子。
#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
}
这背后有什么理由或逻辑可以理解吗?
答案 0 :(得分:1)
在这个例子中,我认为在已分配的内存中堆已经归零是巧合。
的答案中阅读更多内容答案 1 :(得分:0)
始终将变量初始化为有意义的内容。否则允许随机取任何值。
class Student {
public:
int x;
Student(): x(0) {}
};