从C++函数返回多个值

366

从C++函数中返回多个值时是否有一种首选的方法?例如,想象一个将两个整数相除并返回商和余数的函数。我经常见到的一种方式是使用引用参数:

void divide(int dividend, int divisor, int& quotient, int& remainder);

一种变体是返回一个值,并通过引用参数传递另一个值:

int divide(int dividend, int divisor, int& remainder);

另一种方法是声明一个结构体来包含所有的结果,然后返回它:


struct divide_result {
    int quotient;
    int remainder;
};

divide_result divide(int dividend, int divisor);

这些方式中是否有一种通常更受青睐,或者还有其他建议?

编辑:在实际的代码中,可能会有超过两个结果。它们也可能是不同的类型。

23个回答

1
我们可以声明一个函数,使其返回一个结构体类型的用户定义变量或指向它的指针。由于结构体的特性,我们知道在C语言中,一个结构体可以保存多个不对称类型的值(例如一个int变量、四个char变量、两个float变量等等)。

0

如果只有几个返回值,我会使用引用来处理,但对于更复杂的类型,您也可以像这样处理:

static struct SomeReturnType {int a,b,c; string str;} SomeFunction()
{
  return {1,2,3,string("hello world")}; // make sure you return values in the right order!
}

如果返回类型只是暂时的,可以使用“static”将其作用域限制在此编译单元中。

 SomeReturnType st = SomeFunction();
 cout << "a "   << st.a << endl;
 cout << "b "   << st.b << endl;
 cout << "c "   << st.c << endl;
 cout << "str " << st.str << endl;

这绝对不是最美观的方法,但它会起作用。

struct SomeReturnType {int a,b,c; string str;} SomeFunction() 错误:不能在返回类型中定义新类型。 - MatG

-5

快速回答:

#include <iostream>
using namespace std;

// different values of [operate] can return different number.
int yourFunction(int a, int b, int operate)
{
    a = 1;
    b = 2;

    if (operate== 1)
    {
        return a;
    }
    else
    {
        return b;
    }
}

int main()
{
    int a, b;

    a = yourFunction(a, b, 1); // get return 1
    b = yourFunction(a, b, 2); // get return 2

    return 0;
}

我建议看一下其他解决方案,例如 auto&&[result, other_result]=foo();。这样做的好处是,如果 foo 在计算 ab 之前需要进行一些繁重的工作,它不会做额外的工作,并且这是一个标准解决方案,而不是传递 operate,这可能会让其他程序员感到困惑。 - user904963

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接