When I change a parameter inside a function, does

2018-12-31 22:34发布

问题:

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

If I call them in the same file by

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

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

回答1:

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

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



回答2:

Passing by reference is indeed a correct answer, however, C++ sort-of allows multi-values returns using std::tuple and (for two values) 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);
}

This way, you don\'t have to use out-parameters at all.

On the caller side, you can use std::tie to unpack the tuple into other variables:

using std::tie;

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

Hope this helps!



回答3:

You need to pass your variables by reference which means

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


回答4:

as said above, you need to pass by reference to return altered values of \'m\' and \'n\', but... consider passing everything by reference and using const for the params you don\'t want to be altered inside your function i.e.

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


标签: c++