当我更改函数内部的参数时,它也会为调用者更改吗?

Lis*_*isa 16 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;
}
Run Code Online (Sandbox Code Playgroud)

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

trans(center_x,center_y,angle,xc,yc);
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*off 38

由于您使用的是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);
    // ...
}
Run Code Online (Sandbox Code Playgroud)

如果您使用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);
    /* ... */
}
Run Code Online (Sandbox Code Playgroud)

我建议查看C++ FAQ Lite的参考文献,以获取有关如何正确使用参考文献的更多信息.

  • trans(x,y,theta,xc,yc); (5认同)

Chr*_*ung 9

通过引用传递确实是一个正确的答案,但是,C++ sort-of允许使用std::tuple和(对于两个值)返回多值std::pair:

#include <cmath>
#include <tuple>

using std::cos; using std::sin;
using std::make_tuple; using std::tuple;

tuple<double, double> trans(double x, double y, double theta)
{
    double m = cos(theta)*x + sin(theta)*y;
    double n = -sin(theta)*x + cos(theta)*y;
    return make_tuple(m, n);
}
Run Code Online (Sandbox Code Playgroud)

这样,您根本不必使用out参数.

在调用者方面,您可以使用std::tie将元组解压缩为其他变量:

using std::tie;

double xc, yc;
tie(xc, yc) = trans(1, 1, M_PI);
// Use xc and yc from here on
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!