【问题标题】:When I change a parameter inside a function, does it change for the caller, too?当我更改函数内部的参数时,调用者的参数也会改变吗?
【发布时间】:2009-11-09 01:27:31
【问题描述】:

我在下面写了一个函数:

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++


【解决方案1】:

由于您使用的是 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++,我主要应该通过 trans(x, y, theta, &xc, &yc) 或 trans(x, y, theta, xc, yc) 调用;
【解决方案2】:

通过引用传递确实是一个正确的答案,但是,C++ 排序允许使用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);
}

这样,您根本不必使用 out-parameters。

在调用方,您可以使用std::tie 将元组解包到其他变量中:

using std::tie;

double xc, yc;
tie(xc, yc) = trans(1, 1, M_PI);
// Use xc and yc from here on

希望这会有所帮助!

【讨论】:

    【解决方案3】:

    你需要通过引用传递你的变量,这意味着

    void trans(double x,double y,double theta,double &m,double &n) { ... }
    

    【讨论】:

      【解决方案4】:

      如上所述,您需要通过引用传递以返回“m”和“n”的更改值,但是...考虑通过引用传递所有内容并使用 const 作为您不想在内部更改的参数你的功能,即

      void trans(const double& x, const double& y,const double& theta, double& m,double& n)
      

      【讨论】:

        猜你喜欢
        • 2016-03-28
        • 2016-08-30
        • 1970-01-01
        • 2013-06-23
        • 1970-01-01
        • 1970-01-01
        • 2011-10-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多