C++ 当我在函数中更改参数时,调用方是否也会更改参数?

C++ 当我在函数中更改参数时,调用方是否也会更改参数?,c++,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; } 如果我在同一个文件中通过 trans(center_x,center_y,angle,xc,yc); xc和yc的值会改变吗?如果不是,我该怎么办?< p>因为你使用C++,如果你想要 xc>代码>和 yc

我在下面编写了一个函数:

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
yc
的值会改变吗?如果不是,我该怎么办?

< p>因为你使用C++,如果你想要<代码> xc>代码>和<代码> yc>代码>,你可以使用引用:

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

我建议您查看,以获取有关如何正确使用引用的更多信息。

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

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

传递引用确实是正确答案,但是C++类允许使用<代码> STD::tuple < /C> >和(对于两个值)<代码> STD::配对< /代码>:

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

希望这有帮助

如上所述,您需要通过引用传递以返回修改后的'm'和'n'值,但是。。。考虑通过引用传递所有的内容,并使用const作为不希望在函数内更改的参数,即

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

相关问题:,请询问。。。作业问题!请使用堆栈溢出来代替答案键。如果使用C++,在main中我应该用反式(x,y,θ,和xc,yc)或反式(x,y,θ,xc,yc)调用;
void trans(const double& x, const double& y,const double& theta, double& m,double& n)