- 本节主要介绍c++函数多个返回值的实现方式。
-
返回结构体
- 通过返回一个结构体来返回多个值,该实现方式代码的可读性高,便于维护。同时在栈上创建结构体,函数也拥有比较好的性能。示例代码如下:
-
#include <iostream>struct TestResult {std::string s1;std::string s2;int a; };TestResult GetStringMessage() {TestResult tr;tr.s1 = "Hello ";tr.s2 = "pcop!";tr.a = 7;return tr; }int main() {TestResult tr = GetStringMessage();std::cout << tr.s1 << tr.s2 << tr.a << std::endl;std::cin.get();return 0; }
-
在方法的参数中传入接收返回值的变量。这样做的弊端是当要返回的参数太多时,方法的参数将会有很多。
-
#include <iostream>void GetStringMessage(std::string& s1Out, std::string& s2Out) {s1Out = "Pcop!";s2Out = "NIUbi!"; }int main() {std::string s1,s2;GetStringMessage(s1, s2);std::cout << s1 << std::endl;std::cout << s2 << std::endl;std::cin.get();return 0; }
-
通过返回tuple或者pair来返回多个返回值,tuple或者pair在取值的时候相对比较麻烦,而且可读性比较差。
-
#include <iostream> #include <utility> #include <functional>std::tuple<std::string, std::string> GetStringMessage() {std::string s1Out = "Pcop!";std::string s2Out = "NIUbi!";return std::make_tuple(s1Out, s2Out); }int main() {std::string s1 = std::get<0>(GetStringMessage()); std::string s2 = std::get<1>(GetStringMessage());std::cout << s1 << std::endl;std::cout << s2 << std::endl;std::cin.get();return 0; }
-
#include <iostream> #include <utility> #include <functional>std::pair<std::string, std::string> GetStringMessage() {std::string s1Out = "Pcop!";std::string s2Out = "NIUbi!";return std::make_pair(s1Out, s2Out); }int main() {auto source = GetStringMessage();std::string s1 = source.first;std::string s2 = source.second;std::cout << s1 << std::endl;std::cout << s2 << std::endl;std::cin.get();return 0; }