C++传递一个字符串

Jos*_*osh 33 c++ string function

快速可能很明显的问题

如果我有:

void print(string input)
{
  cout << input << endl;
}
Run Code Online (Sandbox Code Playgroud)

我怎么称它为:

print("Yo!");
Run Code Online (Sandbox Code Playgroud)

它抱怨我传入char*而不是std :: string.在电话中有没有办法对它进行类型转换?代替:

string send = "Yo!";
print(send);
Run Code Online (Sandbox Code Playgroud)

谢谢.

In *_*ico 50

你可以编写你的函数来const std::string&:

void print(const std::string& input)
{
    cout << input << endl;
}
Run Code Online (Sandbox Code Playgroud)

或者const char*:

void print(const char* input)
{
    cout << input << endl;
}
Run Code Online (Sandbox Code Playgroud)

两种方式都允许你这样调用它:

print("Hello World!\n"); // A temporary is made
std::string someString = //...
print(someString); // No temporary is made
Run Code Online (Sandbox Code Playgroud)

第二个版本确实需要c_str()调用std::strings:

print("Hello World!\n"); // No temporary is made
std::string someString = //...
print(someString.c_str()); // No temporary is made
Run Code Online (Sandbox Code Playgroud)


Dav*_*ing 7

你应该能够调用print("哟!"),因为有一个std :: string的构造函数,它接受一个const char*.这些单个参数构造函数定义了从它们的aguments到它们的类类型的隐式转换(除非构造函数声明为explicit,而std :: string不是这种情况).你真的试过编译这段代码吗?

void print(std::string input)
{
    cout << input << endl;
} 
int main()
{
    print("yo");
}

它在GCC中编译好.但是,如果您声明了这样的print,void print(std::string& input)则它将无法编译,因为您无法将非const引用绑定到临时(该字符串将是从"yo"临时构造的)


Ebo*_*ike 6

好吧,std::string是一个类,const char *是一个指针.这是两件不同的事情.它很容易从string一个指针(因为它通常包含一个它可以返回的指针),但另一方面,你需要创建一个类型的对象std::string.

我的建议:采用常量字符串而不修改它们const char *的函数应始终作为参数.这样,它们将始终工作 - 使用字符串文字以及std::string(通过隐式c_str()).


sve*_*ens 5

print(string ("Yo!"));
Run Code Online (Sandbox Code Playgroud)

你需要从中创建一个(临时)std::string对象.