C++ compile time error: expected identifier before numeric constant

后端 未结 3 421
死守一世寂寞
死守一世寂寞 2020-11-30 23:55

I have read other similar posts but I just don\'t understand what I\'ve done wrong. I think my declaration of the vectors is correct. I even tried to declare without size bu

相关标签:
3条回答
  • 2020-12-01 00:00

    You cannot do this:

    vector<string> name(5); //error in these 2 lines
    vector<int> val(5,0);
    

    in a class outside of a method.

    You can initialize the data members at the point of declaration, but not with () brackets:

    class Foo {
        vector<string> name = vector<string>(5);
        vector<int> val{vector<int>(5,0)};
    };
    

    Before C++11, you need to declare them first, then initialize them e.g in a contructor

    class Foo {
        vector<string> name;
        vector<int> val;
     public:
      Foo() : name(5), val(5,0) {}
    };
    
    0 讨论(0)
  • 2020-12-01 00:08

    Since your compiler probably doesn't support all of C++11 yet, which supports similar syntax, you're getting these errors because you have to initialize your class members in constructors:

    Attribute() : name(5),val(5,0) {}
    
    0 讨论(0)
  • 2020-12-01 00:17

    Initializations with (...) in the class body is not allowed. Use {..} or = .... Unfortunately since the respective constructor is explicit and vector has an initializer list constructor, you need a functional cast to call the wanted constructor

    vector<string> name = decltype(name)(5);
    vector<int> val = decltype(val)(5,0);
    

    As an alternative you can use constructor initializer lists

     Attribute():name(5), val(5, 0) {}
    
    0 讨论(0)
提交回复
热议问题