Can I avoid an ambiguity, when I declare a fixed length vector in class?

三世轮回 提交于 2019-12-02 10:39:56

问题


I want to declare a vector of 2 elements as a class member. But next code generates an error:

class A {
private:
   std::vector<int> v (2);
   ...
}

The compiler curses about "2" is constant. As I understand, the problem is, the ambiguity arises, because the compiler parses the string of vector declaration as an function declaration (function, that takes "2" as an argument and returns vector of ints).

Question: Can I avoid this ambiguity? How can I do this?

PS: outside the class this vector declaration is parsed correctly.


回答1:


An in-class initialiser has to use braces or the equals sign; so this could be

std::vector<int> v = std::vector<int>(2);

or

std::vector<int> v {0,0};  // Careful! not {2}

Alternatively, you could use old-school initialisation in the constructor(s):

A() : v(2) {}



回答2:


You can safely use this syntax:

std::vector<int> v = std::vector<int>(2);

Alternatively, use brace initialization, but you must be careful: the std::initializer_list<int> constructor will be picked, so to initialize a vector with two value- (therefore zero-) initialized ints you need

std::vector<int> v{0, 0};


来源:https://stackoverflow.com/questions/24679252/can-i-avoid-an-ambiguity-when-i-declare-a-fixed-length-vector-in-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!