Returning multiple values from a C++ function

后端 未结 21 2535
别跟我提以往
别跟我提以往 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:32

    Why do you insist on a function with multiple return values? With OOP you can use a class offering a regular function with a single return value, and any number of additional "return values" like below. The advantage is that the caller has a choice of looking at the extra data members, but is not required to do this. This is the preferred method for complicated data base or networking calls, where lots of additional return info may be needed in case errors occur.

    To answer your original question, this example has a method to return the quotient, which is what most callers may need, and additionally, after the method call, you can get the remainder as a data member.

    class div{
       public:
          int remainder;
    
          int quotient(int dividend, int divisor){
             remainder = ...;
             return ...;
          }
    };
    

提交回复
热议问题