當我更改函數內部的參數時,它也會為調用者更改嗎?我在下面寫了一個函數: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改變?如果沒有,我該怎么辦?
3 回答

三國紛爭
TA貢獻1804條經驗 獲得超7個贊
由于您使用的是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); /* ... */}
我建議查看C ++ FAQ Lite的參考文獻,以獲取有關如何正確使用引用的更多信息。

慕村225694
TA貢獻1880條經驗 獲得超4個贊
通過引用傳遞確實是一個正確的答案,但是,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);}
這樣,您根本不必使用out參數。
在調用者方面,您可以使用std::tie
將元組解壓縮為其他變量:
using std::tie;double xc, yc;tie(xc, yc) = trans(1, 1, M_PI);// Use xc and yc from here on
希望這可以幫助!

慕田峪4524236
TA貢獻1875條經驗 獲得超5個贊
您需要通過引用傳遞變量,這意味著
void trans(double x,double y,double theta,double &m,double &n) { ... }
- 3 回答
- 0 關注
- 575 瀏覽
添加回答
舉報
0/150
提交
取消