2016-10-30 6 views
9

イニシャライザリストを使用して文字列のベクトルを初期化しようとしています。しかし、私はいくつかの奇妙な行動を起こしています。 コンストラクタに複数の引数がある場合に機能しますが、それが唯一の引数である場合はエラーを返します。下記のコードを参考にしてください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; 
} 

私はVisual Studio 2013を使用しています。

+0

作品VS2015 – selbie

+0

@selbieは、Visual Studioのバグですか? – Sourabh

+0

VS2013の最新のサービスパックがインストールされていますか? – selbie

答えて

1

旧バージョンのC++コンパイラを使用しています。 IDEをVS 2015にアップデートしてください。私はあなたのプログラムをg ++で、オプション-std=c++11でテストしました。プログラムはLinuxのg ++​​で動作し、オプションは-std=c++11です。オプションなしの場合-std=c++11プログラムが動作しません。新しいIDEはC++ 11をサポートする必要があります。

+0

VSコミュニティ2015でテストしたところ、うまくいくようです。私はg ++でも動作します。ありがとう! – Sourabh

関連する問題