gpt4 book ai didi

c++ - 当我更改函数内的参数时,调用者也会更改吗?

转载 作者:IT老高 更新时间:2023-10-28 22:16:14 25 4
gpt4 key购买 nike

我在下面写了一个函数:

void trans(double x,double y,double theta,double m,double n)
{
m=cos(theta)*x+sin(theta)*y;
n=-sin(theta)*x+cos(theta)*y;
}

如果我在同一个文件中调用它们

trans(center_x,center_y,angle,xc,yc);

xcyc 的值会改变吗?如果没有,我该怎么办?

最佳答案

由于你使用的是C++,如果你想改变xcyc,你可以使用引用:

void trans(double x, double y, double theta, double& m, double& n)
{
m=cos(theta)*x+sin(theta)*y;
n=-sin(theta)*x+cos(theta)*y;
}

int main()
{
// ...
// no special decoration required for xc and yc when using references
trans(center_x, center_y, angle, xc, yc);
// ...
}

而如果您使用 C,则必须传递显式指针或地址,例如:

void trans(double x, double y, double theta, double* m, double* n)
{
*m=cos(theta)*x+sin(theta)*y;
*n=-sin(theta)*x+cos(theta)*y;
}

int main()
{
/* ... */
/* have to use an ampersand to explicitly pass address */
trans(center_x, center_y, angle, &xc, &yc);
/* ... */
}

我建议查看 C++ FAQ Lite's entry on references有关如何正确使用引用的更多信息。

关于c++ - 当我更改函数内的参数时,调用者也会更改吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1698660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com