C ++ 11默认成员变量值+大括号括起初始化列表

时间:2015-04-15 01:55:40

标签: c++ c++11 gcc

以下代码有效:

   #include <iostream>                                                             

   using namespace std;                                                            

   struct Formula {                                                                
     int x;                                                                   
   };                                                                              

   int main() {                                                                    
    Formula f = {1};                                                              
    return 0;                                                                     
  } 

但是,在添加成员变量的默认值后,它将失败:

   #include <iostream>                                                             

   using namespace std;                                                            

   struct Formula {                                                                
     int x = 10; // Initialize x with a default value 10.                                                            
   };                                                                              

   int main() {                                                                    
    Formula f = {1}; // this line no longer works.                                                           
    return 0;                                                                     
  } 

错误如下:

g++ -std=gnu++11 exp07.cc 
exp07.cc: In function ‘int main()’:
exp07.cc:10:17: error: could not convert ‘{1}’ from ‘<brace-enclosed initializer list>’ to ‘Formula’
   Formula f = {1};

0 个答案:

没有答案
相关问题