在下面的代码中:
#include<iostream>
using namespace std;
class Father
{
public:
int a=11;
void f(){ cout<<"f called"<<endl;}
};
int main(){
Father *obj;
cout <<obj->a<<endl; //I get a garbage value and the compiler issues a warning: 'obj' is used uninitialized in this function
Father f;
cout <<f.a<<endl; // it prints 11
return 1;
}
cout <<obj->a<<endl;
正在打印垃圾值,而不是默认值11,就像上面的一样。他们不是应该打印相同的吗?为什么使用指针而不是直接实例化对象时不使用类成员的默认值?
最佳答案
不,这是UB。
给定Father *obj;
,obj
是default-initialized,其值不确定,
这意味着obj
没有指向任何有效的对象,并且对其取消引用会导致undefined behavior,一切皆有可能。您需要使其指向有效对象,例如
Father f;
Father *obj = &f;
cout <<obj->a<<endl;
要么
Father *obj = new Father;
cout <<obj->a<<endl;
delete obj;
Father f;
也执行default-initialization。作为类类型,f.a
初始化为值11
。顺便说一句:C++ 11支持Default member initializer(在
int a=11;
类中编写Father
时),请尝试使用C++ 11(或更高版本)模式编译代码。