如何在 C++ 中支撑自定义类的初始化向量?
拥有此简单的代码:
#include <iostream>
#include <vector>
#include <string>
class Person{
public:
Person(std::string const& name) : name(name) {}
std::string const& getName() const {
return name;
}
private:
std::string name;
};
int main(){
// std::vector<int> ar = {1,2,3};
std::vector<Person> persons = {"John", "David", "Peter"};
}
我会遇到错误:
could not convert ‘{"John", "David", "Peter"}’ from ‘<brace-enclosed initializer list>’ to ‘std::vector<Person>’
那么为什么启用int
s的向量来支撑initialize,但是使用隐式构造函数自定义类(带有std :: String :: String
)不能?以及如何启用它?
Having this simple code:
#include <iostream>
#include <vector>
#include <string>
class Person{
public:
Person(std::string const& name) : name(name) {}
std::string const& getName() const {
return name;
}
private:
std::string name;
};
int main(){
// std::vector<int> ar = {1,2,3};
std::vector<Person> persons = {"John", "David", "Peter"};
}
I am getting error:
could not convert ‘{"John", "David", "Peter"}’ from ‘<brace-enclosed initializer list>’ to ‘std::vector<Person>’
So why vector of int
s is enabled to brace-initialize, but custom class with implicit constructor (with std::string
) cannot? And how to enable it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您只需要更多的牙套:
You just need more braces:
问题是您在初始化列表中使用(C 风格)字符串文字,但向量包含
std::string
。解决此问题的一种方法是传递 std::string 对象。这是一种方法:或者,您可以为每个对象使用大括号初始值设定项,如另一个答案中所建议的:
The issue is that you are using (C-style) string literals in the initialization list, but the vector holds
std::string
. One way to work around this is to passstd::string
objects. Here is one way to do it:Alternatively, you can use brace initializers for each object, as suggested in another answer:
您可以向您的类添加另一个接受
const char*
的构造函数,它应该可以工作或附加大括号,就像另一个答案中建议的那样。
You can add another constructor accepting
const char*
to your class and it should workOr additional braces, like suggested in another answer.