Returning multiple values from a C++ function

后端 未结 21 2538
别跟我提以往
别跟我提以往 2020-11-22 01:04

Is there a preferred way to return multiple values from a C++ function? For example, imagine a function that divides two integers and returns both the quotient and the rema

21条回答
  •  青春惊慌失措
    2020-11-22 01:50

    I would just do it by reference if it's only a few return values but for more complex types you can also just do it like this :

    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!
    }
    

    use "static" to limit the scope of the return type to this compilation unit if it's only meant to be a temporary return type.

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

    This is definitely not the prettiest way to do it but it will work.

提交回复
热议问题