解决方案一:字符串output 将始终为空白,您的代码仍为当前形式。这是因为output 仅在作为参数传递给example_method 时才被复制到另一个字符串实例。 out 是另一个字符串实例,其值为output。换句话说,这意味着string out=output,仅此而已。代码行out = in; 仅将in 的值复制到out。
So, actually the value of output is not being acted upon at all。
为了使output 的值生效,您必须传递它的值by reference,或者换句话说,您必须将address of output 传递给example_method,并且该地址将由指针获取。 这样,通过指针所做的任何更改也会影响 example_method 范围之外的输出字符串的值。
以下代码段说明了我的观点:
#include <iostream>
#include <string>
using namespace std;
void example_method(string another_string, string *pointer_to_output);
int main()
{
string input="I am a test string";
string output="";
//cout<<"Enter input string"<<endl;
//cin>>input;
example_method(input,&output);
cout<<"The result is: "<<output<<endl;
return 0;
}
void example_method(string another_string, string *pointer_to_output)
{
*pointer_to_output=another_string;
}
解决方案二:
为什么不简单地将example_method 的return type 从void 更改为std::string?通过这种方法,void example_method(string in, string out); 在 main 上方的声明中更改为 string example_method(string in, string out);。
并使用cout<<example_method(input, output);将返回的输出字符串输出到屏幕上
这样您就可以使用cout 简单地将输出返回到屏幕。
这样你的代码就可以工作了,它实现了你想要做的事情,并且没有真正需要使用指针。
修改后的代码:
#include <string>
using namespace std;
string example_method(string in, string out);
int main(){
string input;
string output;
cin >> input;
cout<<example_method(input, output);
// cout << "The result is: " << output << endl;
return 0;
}
string example_method(string in, string out){
out = in;
return out;
}
希望这会有所帮助!