2009-11-09 7 views
13

나는 아래 함수를 작성했습니다 :함수 내에서 매개 변수를 변경하면 호출자도 변경됩니까?

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

하여 동일한 파일을 호출하는 경우 것 xcyc 변화의 가치인가? 그렇지 않다면 어떻게해야합니까? 당신이 xcyc 변경하려는 경우

+0

관련 질문 예 : http://stackoverflow.com/questions/410593/pass-by-reference-value-in-c, http://stackoverflow.com/questions/1322517/passing -a-modifiable-parameter-to-c-function – outis

+0

요청 요청 ... 숙제 문제! 대답 키 이외에는 스택 오버플로를 사용하십시오. – bobby

답변

30

것은 당신이, 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() 
{ 
    // ... 
    // 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's entry on references을 확인하는 것이 좋습니다.

+0

C++을 사용하는 경우, trans (x, y, theta, & xc, & yc) 또는 trans (x, y, theta, xc, yc)로 호출해야하는 경우 주저없이 – Lisa

+0

고맙습니다. – Lisa

+4

트랜스 (x, y, 세타, xc, yc); – Artelius

1

당신은 참으로 정답은, 그러나, C++의 종류가-의 std::tuple과 (두 값) std::pair를 사용하여 반환 다중 값을 허용입니다 참조로 전달

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

을 의미 참조하여 변수를 전달해야 :

#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-parameters를 전혀 사용할 필요가 없습니다.

발신자 측면에서

, 다른 변수로 튜플을 풀고 std::tie를 사용할 수 있습니다

using std::tie; 

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

희망이 도움이!

0

위와 같이 'm'과 'n'의 변경된 값을 반환하려면 참조로 전달해야하지만 ... 참조로 모든 것을 전달하고 변경하지 않으려는 매개 변수에 대해 const를 사용하는 것을 고려하십시오. 함수 내부

void trans(const double& x, const double& y,const double& theta, double& m,double& n) 
관련 문제