1. 通过引用参数:
#include <iostream>// 通过引用参数实现多个返回值
void multipleReturns(int a, int b, int& sum, int& product) {sum = a + b;product = a * b;
}int main() {int x = 3, y = 4, resultSum, resultProduct;multipleReturns(x, y, resultSum, resultProduct);std::cout << "Sum: " << resultSum << std::endl;std::cout << "Product: " << resultProduct << std::endl;return 0;
}
2. 通过结构体:
#include <iostream>// 使用结构体封装多个返回值
struct Result {int sum;int product;
};// 返回结构体
Result multipleReturns(int a, int b) {Result result;result.sum = a + b;result.product = a * b;return result;
}int main() {int x = 3, y = 4;Result result = multipleReturns(x, y);std::cout << "Sum: " << result.sum