I am trying to push a string in a string vector, like below
void Node::set_val(string &val)
{
this->val.push_back(val);
}
But when I try to call it as below
Obj.set_val("10h;");
I get the below error,
error: no matching function for call to 'Node::set_val(const char [5])'
I assumed that the string in " " is same as string
in c++, Why do I get such an error? What has to be changed below?
You are taking in a
std::string
by non-const reference. Non-const references cannot bind to rvalues, like"10h;"
, so you can't pass literals in to that function.If you aren't going to modify the argument, you should take your argument by reference-to-const:
This way, a temporary
std::string
will be constructed from yourconst char[5]
and passed in toset_val
.You could improve this by taking in the
string
by value andmove
ing it into thevector
:This prevents you from making some unnecessary copies.