C ++传递一个字符串 [英] C++ Pass A String
本文介绍了C ++传递一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有:
void print(string input)
{
cout<<输入< ENDL;
}
我如何称呼它:
print(Yo!);
它抱怨我传入char *,而不是std :: string。有没有办法在通话中对它进行类型转换?而不是:
string send =Yo!;
print(send);
谢谢。
解决方案
您可以编写函数来获取 const std :: string&
:
void print(const std :: string& input)
{
cout<<输入< ENDL;
$ / code>
或者 const char *
:
pre $ void print(const char * input)
{
cout<<输入< ENDL;
}
这两种方式都可以让你像这样调用它:
print(Hello World!\\\
); //临时文件被创建
std :: string someString = // ...
print(someString);第二个版本需要 c_str() / code>被称为 std :: string
s: print(Hello World!\\\
); //暂时没有做成
std :: string someString = // ...
print(someString.c_str()); //暂时没有做成
Quick probably obvious 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);
Thanks.
解决方案 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
这篇关于C ++传递一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文