Pass a string in C++
Quick probably obvious 开发者_JAVA百科question.
If I have:
void print(string input)
{
cout << input << endl;
}
How do I call it like so:
print("Yo!");
It complains that I'm passing in char *, instead of std::string. Is there a way to typecast it, in the call? Instead of:
string send = "Yo!";
print(send);
You can write your function to take a const std::string&
:
void print(const std::string& input)
{
cout << input << endl;
}
or a const char*
:
void print(const char* input)
{
cout << input << endl;
}
Both ways allow you to call it like this:
print("Hello World!\n"); // A temporary is made
std::string someString = //...
print(someString); // No temporary is made
The second version does require c_str()
to be called for std::string
s:
print("Hello World!\n"); // No temporary is made
std::string someString = //...
print(someString.c_str()); // No temporary is made
You should be able to call print("yo!") since there is a constructor for std::string which takes a const char*. These single argument constructors define implicit conversions from their aguments to their class type (unless the constructor is declared explicit which is not the case for std::string). Have you actually tried to compile this code?
void print(std::string input)
{
cout << input << endl;
}
int main()
{
print("yo");
}
It compiles fine for me in GCC. However, if you declared print like this void print(std::string& input)
then it would fail to compile since you can't bind a non-const reference to a temporary (the string would be a temporary constructed from "yo")
Well, std::string
is a class, const char *
is a pointer. Those are two different things. It's easy to get from string
to a pointer (since it typically contains one that it can just return), but for the other way, you need to create an object of type std::string
.
My recommendation: Functions that take constant strings and don't modify them should always take const char *
as an argument. That way, they will always work - with string literals as well as with std::string
(via an implicit c_str()
).
print(string ("Yo!"));
You need to make a (temporary) std::string
object out of it.
For easy stuff like printing, you can define a sort of function in your preprocessors like:
#define print(x) cout << x << endl
The obvious way would be to call the function like this
print(string("Yo!"));
Make it so that your function accepts a const std::string&
instead of by-value. Not only does this avoid the copy and is therefore always preferable when accepting strings into functions, but it also enables the compiler to construct a temporary std::string
from the char[]
that you're giving it. :)
Just cast it as a const char *
.
print((const char *)"Yo!")
will work fine.
精彩评论