使用指针作为函数参数
Using pointers as function parameters
我想做一个使用指针 a s 参数并返回其中一个指针的函数,可能吗?
例:
int* sum(int* x, int* y, int* total){
total=x+y;
return total;
}
我收到此错误:
main.cpp:10:13: error: invalid operands of types 'int*' and 'int*' to binary 'operator+'
如何仅使用指针而不使用引用来做到这一点?
您需要取消引用指针以返回对它们指向的对象的引用:
*total = *x + *y;
但是,在C++中,您可以使用引用来促进此操作:
int sum(int x, int y, int& total)
{
total = x + y;
return total;
}
引用仅用total
声明,因为这是我们需要更改的唯一参数。下面是如何调用它的示例:
int a = 5, b = 5;
int total;
sum(a, b, total);
现在我想起来了,既然我们使用引用来更改值,真的没有必要返回。只需取出 return 语句并将返回类型更改为 void
:
void sum(int x, int y, int& total)
{
total = x + y;
}
或者你可以反过来返回加法而不使用引用:
int sum(int x, int y)
{
return x + y;
}
假设这有效(它不编译,正确):
total=x+y;
它将为您提供指向 x
地址 + y
地址的指针。由于这[几乎]总是无稽之谈,因此编译器不允许将两个指针加在一起。
您真正想要的是添加int *x
和int *y
POINT 的值,并将其存储在total
指向的位置:
*total = *x + *y;
相关文章:
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 当从函数参数中的临时值调用复制构造函数时
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 如何将lambda作为模板类的成员函数参数
- 模板参数推导失败,函数参数/参数不匹配
- 如何在C++中将迭代器作为函数参数传递
- 将函数参数"const char*"转换为"std::string_view"是
- C++ 如何将数组值解压缩为函数参数
- 主函数参数的属性
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 如何定义在用作函数参数时工作的类模板的转换
- 将函数参数完美转发到函数指针:按值传递呢?
- 为什么我不能将引用作为 std::async 的函数参数传递
- 什么..(省略号)作为函数原型中唯一的函数参数,C++?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 接受模板作为函数参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- Arduino 函数参数