c++ - 在 C++ 中使用初始化列表时的奇怪行为

标签 c++ visual-studio c++11 visual-studio-2013 constructor

我正在尝试使用初始化列表来初始化一个字符串 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/

相关文章:

c# - 如何将本地数据库文件添加到 Visual Studio Mac 2017

c# - visual studio 2008 部署项目可以在系统未安装.net 的情况下运行吗?

c++ - typedef 的前向声明

c++ - 为什么标准不允许 "virtual void funcFoo() = 0 { }"?

c++ - void* 指针的指针运算

c++ - 如何中断其他 std::threads C++

visual-studio - 更改 Visual Studio 2019 主题时间控制(主题的日/夜模式)

c++ - 测试静态局部对象的初始化是否线程安全

c++ - 当存在其他构造函数时,如何强制创建默认序列构造函数?

c++ - 你如何将 boost::bind 对象传递给函数?