When I change a parameter inside a function, does it change for the caller, too?
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开发者_StackOverflow社区(center_x,center_y,angle,xc,yc);
will the value of xc
and yc
change? If not, what should I do?
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.
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!
You need to pass your variables by reference which means
void trans(double x,double y,double theta,double &m,double &n) { ... }
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)
精彩评论