当我更改函数内的参数时,调用者的参数也会更改吗? [复制]

2024-04-05

我写了一个函数如下:

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);

将的价值xc and yc改变?如果没有,我该怎么办?


既然你使用的是C++,如果你愿意的话xc and yc要更改,您可以使用参考:

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 的参考条目 https://isocpp.org/wiki/faq/references有关如何正确使用参考文献的更多信息。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当我更改函数内的参数时,调用者的参数也会更改吗? [复制] 的相关文章

随机推荐