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

时间:2011-04-14 06:27:50

标签: c++

我们如何在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=?
    }

我可以使用ot_a = classB.ot_a之类的东西吗?请帮帮我......

6 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

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

  • 返回包含您的返回值的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

答案 2 :(得分:1)

正如在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,因此它们可以避免此问题。

答案 3 :(得分:0)

答案是:references

答案 4 :(得分:0)

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

.之后查看classB运算符,我认为您认为classB是一个对象。不,不是。

ClassB *classB();

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

答案 5 :(得分:0)

如果你可以改变functionB(),那么使用指针作为参数。这样你就可以改变functionB()里面的值,它们将在functionA()中直接改变。