본문 바로가기
코딩/C++

참조(reference)에 의한 전달

by sonysame 2024. 3. 12.

 

참조에 의한 전달은 매우 유용하게 사용할 수 있는 부분!

#include <iostream>
#include <cmath>
#include <vector>

using namespace std;

void addOne(int &y) {
	y = y + 1;
	cout << y << " " << &y << endl;

}

void getSinCos(const double degrees, double& sin_out, double& cos_out) {
	static const double pi = 3.141592;
	const double radians = degrees * pi / 100.0;
	sin_out = sin(radians);
	cos_out = cos(radians);
}

void foo1(int& x) {
	cout << x << endl;
}
void foo2(const int& x) {
	cout << x << endl;
}

void foo3(int*& ptr) {
	cout << ptr << " " << &ptr << endl;
}

void printElement1(int(&arr)[4]) {
	cout << arr << endl;
}
void printElement2(vector<int>& arr) {
	cout << &arr << endl;
}
int main() {
	int x = 5;

	cout << x << " " << &x << endl;
	addOne(x);
	cout << x << " " << &x << endl;

	/////////////////////////////////////////////////////////////////////////////////
	double sin(0.0);
	double cos(0.0);

	getSinCos(30.0, sin, cos);

	cout << sin << " " << cos << endl;
	/////////////////////////////////////////////////////////////////////////////////
	
	//foo1(6); 주소가 없어서 literal은 에러
	foo2(6);
	
	/////////////////////////////////////////////////////////////////////////////////
	int y = 5;
	int* ptr = &y;
	cout << ptr << " " << &ptr << endl;
	foo3(ptr);
	/////////////////////////////////////////////////////////////////////////////////

	int arr1[]{ 1,2,3,4 };
	cout << arr1 << endl;
	printElement1(arr1);

	std::vector<int> arr2={ 1,2,3,4 };
	cout << &arr2 << std::endl;
	
	printElement2(arr2);

	return 0;
}

'코딩 > C++' 카테고리의 다른 글

함수 반환값  (0) 2024.03.13
주소에 의한 전달  (0) 2024.03.12
값에 의한 전달  (0) 2024.03.12
std::array  (0) 2024.03.11
std::vector  (0) 2024.03.11