c++ 初始化

1. 内置类型默认初始化

  内置类型如果没有被显示初始化,则会被编译器默认初始化。初始化会根据①变量类型的不同②变量类型位置,来决定初始化之后的值。但是内置类型如果在函数体内部,则将不被初始化——也就是未定义的,而操作一个未定义的变量会导致错误。与之象必,string 类型会提供默认初始化,所以21行的关于变量  str 操作可以通过。

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 int i; //定义在函数体外,则会被初始化为0
 6 static int k;
 7 
 8 int main()
 9 {
10     cout << i << endl;
11     cout << k << endl;
12     
13     int j;
14     //i = j; // 非法,因为 j 未定义
15     //cout << j << endl; //  同样非法
16 
17     static int g;
18     cout << g << endl;// 合法
19  
20     string str, st("23");
21     st = str; //合法,string类提供了一个合适的默认值
22 }

 

猜你喜欢

转载自www.cnblogs.com/KongHuZi/p/11613144.html