简体   繁体   中英

C++ vector as class member vs in function

When I am using vector as following in a function, I get a variable D and it works.

 vector<int> D(100);

However, when I decide to use this as a class member, I get the following weird error:

error: expected identifier before numeric constant
   99 |     vector<int> D(100);
      |                   ^~~

Could someone explain why this particular error? I can use array in a class as int D[100] .

Default member initializer (since C++11) for member variable only supports equal-sign initializer (and braced-initializer, which doesn't match this use-case).

Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.

You can

vector<int> D = vector<int>(100);

Or use member intializer list. eg

struct x {
    vector<int> D;
    x() : D(100) {}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM