当我改变一个函数里面的参数,它也为调用者改变吗? [英] When I change a parameter inside a function, does it change for the caller, too?

查看:92
本文介绍了当我改变一个函数里面的参数,它也为调用者改变吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了一个函数如下:

I have written a function below:

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 c $ c> yc 更改?

will the value of xc and yc change? If not, what should I do?

推荐答案

因为你使用C ++,如果你想要 xc yc 可以使用参考:

Since you're using C++, if you want xc and yc to change, you can use references:

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);
    // ...
}

你必须传递显式的指针或地址,例如:

Whereas if you were using C, you would have to pass explicit pointers or addresses, such as:

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 ++常见问题解答Lite的参考条目

I would recommend checking out the C++ FAQ Lite's entry on references for some more information on how to use references properly.

这篇关于当我改变一个函数里面的参数,它也为调用者改变吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆