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?
CodePudding user response:
You just need more braces:
std::vector<Person> persons = {
{"John"}, {"David"}, {"Peter"}
};
CodePudding user response:
You can add another constructor accepting const char*
to your class and it should work
class Person{
public:
Person(const char* name): Person(std::string(name)) {}
Person(std::string const& name) : name(name) {}
std::string const& getName() const {
return name;
}
private:
std::string name;
};
Or additional braces, like suggested in another answer.
CodePudding user response:
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 pass std::string
objects. Here is one way to do it:
int main(){
using namespace std::string_literals;
std::vector<Person> persons = {"John"s, "David"s, "Peter"s};
}
Alternatively, you can use brace initializers for each object, as suggested in another answer:
int main(){
std::vector<Person> persons = {{"John"}, {"David"}, {"Peter"}};
}