【问题标题】:strange behavior while using initializer list in c++在 C++ 中使用初始化列表时的奇怪行为
【发布时间】:2017-03-12 15:57:40
【问题描述】:

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

// 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。请帮助。

【问题讨论】:

  • 适用于 VS2015
  • @selbie 那么是视觉工作室的错误吗?
  • 您是否安装了最新的 VS2013 服务包?
  • 在 g++ 上,此代码不起作用。
  • 对于初始化列表{"string1", "string2"},我怀疑Visual Studio 会尝试将char const* 直接转发到您的向量,而不将其包装在初始化列表中。您在第二个示例中明确说明了它,因此它工作正常。

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


【解决方案1】:

您使用的是旧版本的 C++ 编译器。将您的 IDE 更新到 VS 2015。我使用选项 -std=c++11 在 g++ 上测试了您的程序。您的程序在 Linux 上使用 g++ 运行,带有选项 -std=c++11。如果没有选项-std=c++11,您的程序将无法运行。较新的 IDE 应该支持 c++11。

【讨论】:

  • 我在 VS 社区 2015 中进行了测试,它似乎有效。我也使用 g++。谢谢!
猜你喜欢
  • 2021-12-06
  • 2017-03-19
  • 2016-05-14
  • 2011-02-22
  • 2020-07-24
  • 2015-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多