[英]In-class constructor initialisation of a vector in C++
I have class MyClass
as below.我有 class MyClass
如下。 I would like to initilaise the attributes of MyClass
through a constructor.我想通过构造函数初始化MyClass
的属性。 The arguments b_
and c_
should have the defaults {"abc", "_"}
and 0
respectively. arguments b_
和c_
应分别具有默认值{"abc", "_"}
和0
。
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> > >'
.这给了我错误: 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'
.这给了我错误: 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
制作VEC
static也没有解决问题: 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>>
:正确的方法是使用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.这里没有使用optional
,因为要么调用者确实传递了一个向量,要么调用者没有传递向量但随后使用了默认值。 As you want to initialize the member always, passing nullopt
is not an option either.由于您希望始终初始化成员,因此传递nullopt
也不是一个选项。 Hence, just drop the optional
.因此,只需删除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)
{}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.