简体   繁体   中英

In-class constructor initialisation of a vector in C++

I have class MyClass as below. I would like to initilaise the attributes of MyClass through a constructor. The arguments b_ and c_ should have the defaults {"abc", "_"} and 0 respectively.

class MyClass {

    size_t a_;
    std::vector<string> b_;
    size_t c_;

public:

    MyClass(
            size_t a,
            optional<std::vector<string>> b = {"abc", "_"},
            size_t c = 0)
        :   a_(a),
            b_(b),
            c_(c)
        {}
}

This gives me the error: error: could not convert '{"abc", "_"}' from '<brace-enclosed initializer list>' to 'isf::optional<std::vector<std::__cxx11::basic_string<char> > >' .

I then tried:

class MyClass {

    size_t a_;
    std::vector<string> b_;
    size_t c_;

public:
    const std::vector<string> VEC = {"abc", "_"};

    MyClass(
            size_t a,
            optional<std::vector<string>> b = VEC,
            size_t c = 0)
        :   a_(a),
            b_(b),
            c_(c)
        {}
}

This gave me the error: error: invalid use of non-static data member 'MyClass::VEC' .

Making VEC static also did not solve the issue: error: in-class initialization of static data member 'const std::vector<std::__cxx11::basic_string<char> > MyClass::b' of non-literal type

What would be the correct way of declaring a default value for the vector of strings in the constructor?

The right way is to use a std::vector<std::string>> :

MyClass(
            size_t a,
            std::vector<std::string> b = {"abc", "_"},
            size_t c = 0)
        :   a_(a),
            b_(b),
            c_(c)
        {}

There is no use of optional here, because either the caller does pass a vector or the caller does not pass a vector but then the default is used. As you want to initialize the member always, passing nullopt is not an option either. Hence, just drop the optional .

It can be solved in the following way:

class MyClass {

    size_t a_;
    std::vector<string> b_;
    size_t c_;

public:
    const std::vector<string> DEFAULT_VEC = {"abc", "_"};

    MyClass(
            size_t a,
            optional<std::vector<string>> b,
            size_t c = 0)
        :   a_(a),
            b_(b.value_or(DEFAULT_VEC)),
            c_(c)
        {}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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