针对struct和class使用大括哀号初始化的测试

 1 #include <iostream>
 2 using namespace std;
 3 struct struct1{
 4     /*
 5     struct1(){
 6         cout<<"this is output by struct1 !";
 7     }
 8     if add this code block , such errors like 'you must initlizer data number of struct1
 9 
10     by constructor in g++98' will occor in compile time,
11     */
12     int data1 ;
13     double data2 ;
14     string data3 ;
15     /*
16     but if you add the following function without error
17     */
18     void showStruct1(){
19 
20         cout<<"this is output by showStruct1 of struct struct1 ! \n ";
21     }
22 };
23 class class1{
24     public :
25     int data1 ;
26     double data2 ;
27     string data3 ;
28 };
29 int main(){
30     struct1 oneStruct1 = {1, 1.1 , "hello world !"};
31     class1  oneclass1{1, 1.1 , "hello world !"};// errror :
32     // scalar object 'oneclass1' requires one element in initializer ???????????????????
33     //solution : change from 'class1 * oneclass1 = {1,1.1 ....}' to 'class1 oneclass1{......}'
34     return 0;
35 }
36 /*
37 
38 Conclusion : 
39     if struct include some special function like constructor and destructor 
40     
41     will can't initilizer by {} ,
42     
43     class default can't inializer by {}, but you can change access modifiers to public 
44 
45 
46 
47 
48 
49 
50 */

图片 1 

采用大括号初始化struct应该是C语言中之语法。由于C++是朝后兼容C,所以于C++中也支撑该语法。从地方的程序可以见到:

  当struct和class中从来不一定的如构造函数或者析构函数等面向对象特征措施时是足以经过大括声泪俱下进行初始化;但是要struct和class中来标志在面向对象的因素时,就非能够初始化。也就是说,当struct和class体现的是一个数目集合时可以使用大括号,但是要反映的凡如出一辙栽多少类就未能够使用大括号。