首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在c++中使用初始化程序列表时的奇怪行为

问在c++中使用初始化程序列表时的奇怪行为
EN

Stack Overflow用户
提问于 2016-10-30 08:54:18
回答 1查看 230关注 0票数 9

我试图使用初始化程序列表来初始化字符串向量。但我有些奇怪的行为。如果构造函数中有多个参数,它就会工作,但如果这是唯一的参数,则会出现错误。请参阅下面的代码以了解

代码语言:javascript
复制
// 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。请帮帮忙。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40327422

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档