dimanche 30 octobre 2016

strange behavior while using initializer list in c++

I am trying to intialize a vector of strings using initializer list. But I am getting some strange behavior. It works if there are more than one argument in the constructor, but gives an error if that is the only argument. Please see the code below to understand

// 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;
}

I am using visual studio 2013. Please help.

Aucun commentaire:

Enregistrer un commentaire