类数据默认初始化 [英] Class data default initialization
问题描述
我有以下代码:
#include <iostream>
using namespace std;
class Base
{
private:
int i;
char ch;
public:
void showdata()
{
cout<<"Int:"<<i<<endl;
cout<<"Char:"<<ch<<endl;
}
//int pub_data ;
} ;
int main()
{
Base ob;
ob.showdata() ;
//cout<<"Public Data:"<<ob.pub_data<<endl;
return 0;
}
该程序可以编译并正常运行.输出显示i初始化为0,ch初始化为'\ 0'.
如果您注意到我在该程序中已注释掉2条语句.首先是公共数据pub_data的声明,其次在主行中打印该公共数据.
现在的问题是,如果我取消注释这两行,则类(即i,ch,pub_data)的数据成员似乎未初始化,并且在打印时它们将显示垃圾值.
所以我的问题是公共数据在这里有什么不同?
我正在使用g ++ 3.4.6
This program compiles and runs fine. The output shows that i is initialized with 0 and ch is initialized with '\0'.
If you notice i have commented out 2 statements in this program. First the declaration of public data pub_data and second the line inside main printing this public data.
Now here the problem is, if i uncomment these two lines, the data members of class i.e. i, ch, pub_data do not seem to be initialized and when printed, they display junk values.
So my question is what difference public data makes here?
I'm using g++ 3.4.6
推荐答案
int和char都不会自动初始化为0.它发生的事实只是运气.
Neither int's nor char's are automatically initialized to 0. The fact that it happened is just luck.
您需要添加一个执行初始化的构造函数:
You need to add a constructor that does the initialization:
Base() : i(0), ch(0) {}
这篇关于类数据默认初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!