我在 C++ 中遇到了一个问题,我调用了一个为事物分配一些值的函数,但这些分配在函数完成后丢失了。这是我的代码:
#include <iostream>
#include <string>
using namespace std;
void Input(string a, string b){
cout << "Input a: \n";
cin >> a;
cout << endl;
cout << "Input b: \n";
cin >> b;
cout << endl << "Inputen Strings (still in the called function): \n";
cout << a << " " << b << endl << endl;
};
int main(){
string c = "This didn't";
string d = "work";
Input(c,d);
cout << "Inputen Strings (now in the main function): \n";
cout << c + " " + d << endl;
return 0;
};
因此,每当我运行它时,(输入“Hello”,然后输入“World”)程序运行如下:
Input a:
Hello
Input b:
World
输入字符串(仍在被调用函数中):
你好世界
输入字符串(现在在主函数中):
这不起作用
我不知道为什么它只是暂时保存这些值。任何帮助表示赞赏!
更改方法签名以接受变量“&”的地址
void Input(string &a, string &b)
如果没有“&”运算符,您只是将变量的副本发送到函数中,而使用“&”地址运算符,您将通过引用传递变量
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)