我试图使用初始化程序列表来初始化字符串向量。但我有些奇怪的行为。如果构造函数中有多个参数,它就会工作,但如果这是唯一的参数,则会出现错误。请参阅下面的代码以了解
// 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;
}我正在使用2013。请帮帮忙。
发布于 2016-10-30 09:25:48
您使用的是C++编译器的旧版本。将IDE更新为VS 2015。我在g++上用选项-std=c++11测试了您的程序。您的程序在Linux上的g++中使用-std=c++11选项。如果没有选项-std=c++11,您的程序就无法工作。较新的IDE应该支持c++11。
https://stackoverflow.com/questions/40327422
复制相似问题