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?
You just need more braces:
std::vector<Person> persons = {
{"John"}, {"David"}, {"Peter"}
};