在类中声明固定长度的向量时,可以避免歧义吗?

在类中声明固定长度的向量时,可以避免歧义吗?

问题描述:

我想将2个元素的向量声明为类成员.但是下一个代码会生成错误:

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);
   ...
}

编译器对"2"的诅咒是恒定的.据我了解,问题在于,由于编译器将向量声明的字符串解析为函数声明(函数,将"2"作为参数并返回ints的向量),因此产生了歧义.

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:在类之外,此向量声明已正确解析.

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

类内初始化程序必须使用大括号或等号;所以可能是

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

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

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

或者,您可以在构造函数中使用老式的初始化方法:

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

A() : v(2) {}