從 C++ 函式返回多個值


在 C 或 C++ 中,我們無法直接從函式返回多個值。在本節中,我們將看到如何使用一些技巧從一個函式返回多個值。

我們可以使用稱為“按地址呼叫”或“按引用呼叫”的方法從函式返回多個值。在呼叫函式中,我們將使用兩個變數來儲存結果,並且該函式將採用指標型別資料。因此,我們必須傳遞資料地址。

在這個示例中,我們將看到如何定義一個函式,該函式可以從一個函式返回兩個數字相除後的商和餘數。

按地址呼叫

示例

#include<iostream>
using namespace std;
void div(int a, int b, int *quotient, int *remainder) {
   *quotient = a / b;
   *remainder = a % b;
}
main() {
   int a = 76, b = 10;
   int q, r;
   div(a, b, &q, &r);
   cout << "Quotient is: "<< q <<"\nRemainder is: "<< r <<"\n";
}

輸出

Quotient is: 7
Remainder is: 6

按引用呼叫

示例

#include<iostream>
using namespace std;
void div(int a, int b, int "ient, int &remainder) {
   quotient = a / b;
   remainder = a % b;
}
main() {
   int a = 76, b = 10;
   int q, r;
   div(a, b, q, r);
   cout << "Quotient is: "<< q <<"\nRemainder is: "<< r <<"\n";
}

輸出

Quotient is: 7
Remainder is: 6

更新日期:2019-07-30

9K+ 瀏覽次數

開啟您的職業

完成課程認證

開始學習
廣告
© . All rights reserved.