C++/class
class_lab11.cpp 참조에 의한 호출
year.number
2022. 6. 8. 14:29
값에 의한 호출
1. int형, double형, ...
2. 지역변수이기 때문에 변수의 값을 교환할 수 없다.
참조에 의한 호출(포인터 이용)
같은 메모리값을 공유하기 때문에 변수의 값을 교환할 수 있다.
Key Point
1. 값을 교환하는 방법
int tmp;
tmp = *px;
*px = *py;
*py = tmp;
2. 값에 의한 호출과 참조에 의한 호출 차이점
- swap(int 형 변수 a,b)
- swap(&a, &b)
//
// main.cpp
// pointer II
//
// Created by yeonsu on 2022/06/08.
//
#include <iostream>
using namespace std;
// ====================== < 값에 의한 호출 > =======================
void swap(int x, int y);
// ====================== < 참조에 의한 호출 > ======================
void swap(int *px, int *py); //포인터 이용
int main(){
// ====================== < 값에 의한 호출 > =======================
cout << "\n<값에 의한 호출>\n\n";
int a = 100, b = 200;
cout << "swap() 호출 전 : x = " << a << ", y = " << b << endl;
swap(a, b);
cout << "swap() 호출 후 : x = " << a << ", y = " << b << endl;
// ====================== < 참조에 의한 호출 > ======================
cout << "\n\n<참조에 의한 호출>\n\n";
a = 100, b = 200;
cout << "swap() 호출 전 : *px = " << a << ", *py = " << b << endl;
swap(&a,&b);
cout << "swap() 호출 후 : *px = " << a << ", *py = " << b << endl << endl;
return 0;
}
// ====================== < 값에 의한 호출 > =======================
void swap(int x, int y){
int tmp;
cout << "In swap(): x = " << x << ", y = " << y << endl;
tmp = x;
x = y;
y = tmp;
cout << "In swap(): x = " << x << ", y = " << y << endl;
}
// ====================== < 참조에 의한 호출 > ======================
void swap(int *px, int *py){
int tmp;
cout << "In swap(): *px = " << *px << ", *py = " << *py << endl;
tmp = *px;
*px = *py;
*py = tmp;
cout << "In swap(): *px = " << *px << ", *py = " << *py << endl;
}
실행결과

함수가 2개 이상의 결과를 반환해야 하는 경우(slope.cpp)
[기본 개념] 함수는 1개의 반환값만을 가질 수 있다.
참조에 의한 호출을 이용해서 기울기와 y절편을 반환값으로 가질 수 있는 코드를 작성해보자.
//
// slope.cpp
// pointer II
//
// Created by yeonsu on 2022/06/08.
//
#include <iostream>
using namespace std;
int get_line_parameter(int x1, int y1, int x2, int y2, float *slope, float *yintercept){
if (x1 == x2){
return -1; //위치 동일 -> 수직선이 되기 때문에 기울기값을 구할 수 없음
}
else{
*slope = (float)(y2-y1) / (float)(x2-x1);
*yintercept = y1 - (*slope) * x1;
}
return 0;
}
int main(){
float s, y;
if(get_line_parameter(3,3,6,6, &s, &y) == -1)
cout << "에러" << endl;
else
cout << "기울기는 " << s << endl << "y절편은 " << y << endl;
return 0;
}
실행결과
