• 함수의 인자 전달 방식

함수의 인자 전달방식에는 총 세가지가 있다.

Call by value, Call by address, Call by reference.

그중 value와 address를 먼저 보자.


Call by value

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
 
using namespace std;
 
void swap(int a, int b){
    int temp=a;
    a=b;
    b=temp;
}
int main(){
    int m=2, n=9;
    swap(m, n);
    cout<<m<<' '<<n<<endl;
    return 0;
}
cs

출력값

2 9


변하지 않았다. 그저 값만 복사해서 전달했으므로, swap함수 종료와 동시에 swap내부의 변수들은 모두 사라진다.


Call by address

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
 
using namespace std;
 
void swap(int *a, int *b){
    int temp=*a;
    *a=*b;
    *b=temp;
}
int main(){
    int m=2, n=9;
    swap(&m, &n);
    cout<<m<<' '<<n<<endl;
    return 0;
}
cs

출력값

9 2


값이 서로 바뀌었다. 주소 자체에 값을 바꿔 넣었기 때문에 swap함수가 종료되면 바뀌어 있다.



  • 함수 호출시 객체 전달

Call by value 방식으로 객체를 전달하면, 다음과 같은데

1
2
3
4
5
6
7
8
9
void increase(Circle c){
    int r = c.getRadius();
    c.setRadius(r+1);
}
int main(){
    Circle waffle(30);
    increase(waffle);
    cout<< waffle.getRadius() <<endl;
}
cs

이때 waffle의 radius는 30이다.


하지만 Call by address방식으로 객체를 전달하면 다음과 같다.

1
2
3
4
5
6
7
8
9
void increase(Circle *c){
    int r = c->getRadius();
    c->setRadius(r+1);
}
int main(){
    Circle waffle(30);
    increase(&waffle);
    cout<< waffle.getRadius() <<endl;
}
cs

이렇게 하면 waffle의 radius는 1이 증가한 31이 출력이 된다.



  • 객체 치환 및 객체 리턴

객체 치환 시 객체의 모든 데이터가 비트단위로 복사된다.

1
2
3
4
5
6
7
8
9
10
11
Circle getCircle(){    //객체를 리턴하는 함수
    Circle tmp(30);
    return tmp;    //객체를 리턴
}
int main(){
    Circle c;    //객체 생성
    cout<<c.getArea()<<endl;    //3.14출력
    
    c = getCircle(); //radius=30인 객체를 c에 복사
    cout<<c.getArea()<<endl;     //2826
}
cs










Posted by Jyoel :