在使用一些遗留代码的项目中工作时,我发现了这个功能:
std::vector<std::string> Object::getTypes(){
static std::string types [] = {"type1","type2", "type3"};
return std::vector<std::string> (types , types +2);
}
Run Code Online (Sandbox Code Playgroud)
我可能会把它写成:
std::vector<std::string> Object::getTypes(){
std::vector<std::string> types;
types.push_back("type1");
types.push_back("type2");
types.push_back("type3");
return types;
}
Run Code Online (Sandbox Code Playgroud)
这仅仅是一种风格选择还是我缺少的东西?任何帮助将不胜感激.对不起,如果这太基础了.
更新: 实际上发现覆盖相同方法的不同类可以这样或那样做,所以它更加含糊不清.我会让它们都一样,但如果有的话,我会更喜欢更好的方法.
编辑
请注意,上面的遗留代码不正确,因为它只使用数组的前两个元素初始化向量.但是,此错误已在评论中讨论过,因此应予以保留.
正确的初始化应该如下所示:
...
return std::vector<std::string> (types, types + 3);
...
Run Code Online (Sandbox Code Playgroud)