对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 */
使用大括号初始化struct应该是C语言中的语法。由于C++是向后兼容C,所以在C++中也支持该语法。从上面的程序可以看出:
当struct和class中没有特定的像构造函数或者析构函数等面向对象特征方法时是可以通过大括号进行初始化;但是如果struct和class中有标志着面向对象的元素时,就不能初始化。也就是说,当struct和class体现的是一个数据集合时可以使用大括号,但是如果体现的是一种数据类型就不能使用大括号。