在类中初始化变量

时间:2012-11-30 18:00:00

标签: c++ string vector

我需要以这种方式在类中初始化vector

vector<string> test("hello","world");

但是当我这样做时,编译器将它识别为一个函数,并给我一些错误 错误:字符串常量之前的预期标识符等。

当我这样做时

vector<string> test = ("hello","world") 

没关系..有没有办法以vector<string> test("xx")的方式做到这一点?

1 个答案:

答案 0 :(得分:5)

std :: vector中没有这样的构造函数可以让你像那样初始化它。而你的第二个例子评估为"world"(这是,运算符所做的),这是向量中的最终结果。

如果要在声明时初始化向量,请使用初始化列表:

vector<string> test = {"hello", "world"};

确保使用C ++ - 11模式构建源代码,以实现此目的。如果您没有兼容C ++ - 11的编译器,则必须在以后将值添加到向量:

vector<string> test;
test.push_back("hello");
test.push_back("world");