It is not working because the argument has to be a const
reference:
void foo( const std::string& s )
// ^^^^^
foo( "bar" ); // will work now
سؤال
Let's say I have function foo(string& s)
. If I would get C string
, foo(char* s)
, I would simply call the function as foo("bar")
.
I wonder if I can somehow do it in the C++ String
?
Somehow to shorten this:
string v("bar");
foo(v)
I'm using Linux GCC C++.
المحلول
It is not working because the argument has to be a const
reference:
void foo( const std::string& s )
// ^^^^^
foo( "bar" ); // will work now
نصائح أخرى
foo
to only read from the argument you should write foo(const string& s)
. foo
to save the string somewhere (a class member..) you should write foo(string s)
. Both versions allow you to write foo("bar");
which would't make any sense with a non const reference.
You could also try foo(string("bar"));
to get your desired results, but since it is expecting a reference this wont work either.
So that means that your best bet is overloading for const char *
to call the string method (this way you maintain only one method).
The std::string
class does have an implicit conversion from const char*
, so normally, passing a string literal into a function taking std::string
works just fine.
Why it fails in your case is that the function takes its parameter as a non-const lvalue reference, and thus it requires an actual std::string
lvalue to operate on.
If the function actually wants to take a non-const lvalue reference (i.e. it modifies the argument), you have to create an lvalue std::string
and pass it (just like you do).
If the function does not modify the argument, change it to take by const-reference (const std::string&
) or by value (std::string
) instead; for both of these, passing an rvalue (like the std::string
created by implicit conversion from const char*
) will work and you can thus call the function with string literals.