亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

當我更改函數內部的參數時,它也會為調用者更改嗎?

當我更改函數內部的參數時,它也會為調用者更改嗎?

C++
江戶川亂折騰 2019-07-23 15:09:28
當我更改函數內部的參數時,它也會為調用者更改嗎?我在下面寫了一個函數: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 ++,如果您想要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的參考文獻,以獲取有關如何正確使用引用的更多信息。


查看完整回答
反對 回復 2019-07-23
?
慕村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

希望這可以幫助!



查看完整回答
反對 回復 2019-07-23
?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

您需要通過引用傳遞變量,這意味著

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


查看完整回答
反對 回復 2019-07-23
  • 3 回答
  • 0 關注
  • 575 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號