你当然可以在main()
中定义它们并通过引用传递它们。但这是sl。。
如果你要分析这种情况,firstsplit
和secsplit
是你的函数计算。
因此,你的函数应该做的是返回这些值。这是一个函数的功能:它计算一些东西并返回它。
这样做的一种方法是简单地返回std::pair
。
std::pair<std::string, std::string> strParse(const string& a) { //parse line read input
int b = a.find("-");
std::string firstsplit = a.substr(0, b);
std::string secsplit = a.substr(b + 1);
return std::make_pair(firstsplit, secsplit);
}
但是,这将导致更多的工作,更重写,如果你的功能可能还需要返回别的东西,或其他一些替代性的结果,如错误指示。
最灵活的做法,是由函数返回一个类:
class parse_results {
public:
std::string firstsplit;
std::string secsplit;
};
parse_results strParse(const string& a) { //parse line read input
parse_results ret;
int b = a.find("-");
ret.firstsplit = a.substr(0, b);
ret.secsplit = a.substr(b + 1);
return ret;
}
然后,如果你需要有什么样的位置返回更多的信息,这可以简单地添加到parse_results
类。
@为什么如果你定义'main'中的变量不能在函数中使用(暗示你将它们当作参数传递)? – KostasRim
您可能需要将字符串传递到函数中,以便您可以填充它们,或者您需要将它们从函数中传递出来,形成一对。 – NathanOliver