处理具有多个输出参数的函数

Handling functions with more than one output parameters

本文关键字:参数 函数 输出 处理      更新时间:2023-10-16

我们如何在C++中处理多个输出参数。我是C++的初学者,目前我正在尝试编写一个函数a,它调用其他类的另一个函数B,函数B总共由6个参数组成,其中三个是输入参数,其余三个是输出参数。如何访问函数A中的所有三个输出参数?我试着用下面的方法。。。如果我出错了,有人能帮我更正代码吗。。?朋友们,请帮帮我。。

class A ::functionA()
   {
      int in_a=1;
      string in_b= "name";
      int in_c=3; 
      int ot_a=0;
      int ot_b=0;
      string ot_s1="" 
      ClassB *classB();
      classB = classB.functionB(in_a,in_b,in_c,ot_a,ot_b,ot_s1); //is this way correct?
      ot_a= ? ;
      ot_b=? ;
      ot_s1=?
    }

我能用ota=classB.ota这样的词吗?请帮我…

您把C++的基本语法搞错了。ClassB *classB();不创建任何对象,它声明了返回ClassB*的函数classB的函数原型。要创建一个对象,您应该执行ClassB b;,然后使用b。如果函数通过引用获取其参数,则输出变量将由函数正确填充。

对于多个返回值,通常有两个选择:

  • 返回包含返回值的struct
  • 在每个引用中传递返回值

两个例子都展示了:

// first approach, struct return
struct myReturns{
  int int_return;
  float float_return;
};
myReturns MyFunc(int param1, char* param2, ...){
  // do some stuff with the parameters
  myReturns ret;
  ret.int_return = 42;
  ret.float_return = 13.37f;
  return ret;
}
// calling it:
myReturns ret = MyFunc(/*pass your parameters here*/);
int i = ret.int_return;
float f = ret.float_return;
// second approach, out parameters
void MyFunc(int inParam1, char* inParam2, int& outInt, float& outFloat){
  // do some stuff with the parameters
  outInt = 42;
  outFloat = 13.37f;
}
// calling it:
int i;
float f;
MyFunc(/*your parameters here*/,i,f);
// i and f are now changed with the return values

正如Xeo的回答中所提到的,您可以使用返回结构或引用。还有另一种可能性,使用指针。指针允许你做一件事:如果你调用的函数可以用来计算多个信息,但你不想要所有的信息,你可以传递NULL作为指针的值,这样函数就知道它不需要填充这些信息。

当然,你调用的函数需要这样设计,它不是自动的。

void f()  
{   
    type1* p1 = new type1();  
    type2* p2 = NULL
    g(p1, p2);
}
void g(type1* param1, type2* param2)  
{
    //Do some computation here
    if (param1 != NULL)
    {
        //Do something here to fill param1
    }
    if (param2 != NULL)
    {
        //Do something here to fill param2
    }
}

但一般来说,最好尽可能使用引用,必要时使用指针。如果函数不能处理传递给它的指针为NULL的情况,那么它将以崩溃告终。引用不能为NULL,因此可以避免此问题。

答案是:引用。

ClassB *classB();
classB = classB.functionB(in_a,in_b,in_c,ot_a,ot_b,ot_s1);

通过在classB之后查找.运算符,我假设您认为classB是一个对象。不,不是。

ClassB *classB();

上面的语句说-classB()是一个不带参数的函数,返回类型是对ClassB的引用。

如果可以更改函数B((,则使用指针作为参数。通过这种方式,您可以更改函数B((中的值,它们将直接在函数A((中更改。