我正在尝试使用初始化列表来初始化一个字符串 vector 。但是我有一些奇怪的行为。 如果构造函数中有多个参数,它会起作用,但如果这是唯一的参数,则会出错。请看下面的代码来理解
// option.h file
#ifndef __OPTION_H__
#define __OPTION_H__
#include <string>
#include <vector>
namespace CppOptParser {
class Option
{
std::vector<std::string> names;
std::string description;
public:
// constructors
Option(const std::vector<std::string>& names);
Option(const std::vector<std::string>& names, const std::string& description);
// destructor
~Option();
};
} // namespace CppOptParser
#endif /* __OPTION_H__ */
// option.cpp file
#include "option.h"
namespace CppOptParser {
Option::Option(const std::vector<std::string>& names)
{
this->names = names;
}
Option::Option(const std::vector<std::string>& names, const std::string& description)
{
this->names = names;
this->description = description;
}
Option::~Option() {}
} // namespace CppOptParser
// main.cpp file
#include "option.h"
#include <iostream>
using namespace CppOptParser;
int main(int argc, char *argv[])
{
Option *opt = new Option({ "f", "filename"}); // gives error -- error C2440: 'initializing' : cannot convert from 'initializer-list' to 'CppOptParser::Option'
Option *opt1 = new Option({"f", "filename"}, "output file name"); // works fine
std::cin.get();
return 0;
}
我正在使用 visual studio 2013。请帮忙。
最佳答案
您使用的是旧版本的 C++ 编译器。将您的 IDE 更新为 VS 2015。我使用选项 -std=c++11
在 g++ 上测试了您的程序。您的程序使用选项 -std=c++11
在 Linux 上的 g++ 中运行。如果没有选项 -std=c++11
,您的程序将无法运行。较新的 IDE 应该支持 c++11。
关于c++ - 在 C++ 中使用初始化列表时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40327422/