繁体   English   中英

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

[英]strange behavior while using initializer list in c++

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

// 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年的visual studio。请帮忙。

您正在使用旧版本的C ++编译器。 将IDE更新到VS 2015.我使用选项-std=c++11在g ++上测试了您的程序。 您的程序在Linux上使用g ++工作,选项为-std=c++11 没有选项-std=c++11你的程序不起作用。 较新的IDE应该支持c ++ 11。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM