处理具有多个输出参数的函数
Handling functions with more than one output parameters
我们如何在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((中更改。
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类