使用指针作为函数参数

Using pointers as function parameters

本文关键字:函数 参数 指针      更新时间:2023-10-16

我想做一个使用指针 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 *xint *y POINT 的值,并将其存储在total指向的位置:

*total = *x + *y;