在类中声明固定长度的向量时,可以避免歧义吗? [英] Can I avoid an ambiguity, when I declare a fixed length vector in class?

查看:49
本文介绍了在类中声明固定长度的向量时,可以避免歧义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将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) {}

这篇关于在类中声明固定长度的向量时,可以避免歧义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆