本着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体现的是一个多少集合时可以动用大括声泪俱下,但是一旦反映的是均等种多少列就不可知利用大括号。