C/C++ 函數返回多個參數
轉自:https://blog.csdn.net/onlyou2030/article/details/48174461
筆者是 Python 入門的,一直很困惑 C/C++ 中函數如何返回多個參數。
如果一個函數需要返回多個參數,可以采用以下兩種方法:
傳引用或指針作為入參,函數體內直接修改地址處的內容
第一種方法是將返回值作為寫參數。
#include <iostream>
#include <string>
using namespace std;void fun(int &a, char &b, string &c)
{a = 1;b = 'b';c = "test";
}int main()
{int a;char b;string c;fun(a,b,c);cout << a << " " << b << " " << c << endl;
}
返回結構體
第二種方法是定義一個結構,返回指向該結構的指針。
#include <iostream>
#include <string>
using namespace std;struct result
{int a;char b;string c;
};result * fun()
{result *test=new result;test->a = 1;test->b = 'b';test->c = "test";return test;
}int main()
{result *test;test=fun();cout << test->a << " " << test->b << " " << test->c << endl;delete test;return 1;
}