이것을 사용하는 상황은 함수를 재사용할때 쓸수 있을 것이다.
디폴트 인자는 하나 혹은 모든 함수에 적용해도 상관없다.
코드 최적하 문서들을 찾아보면 함수에 인자의 갯수가 적을수록 함수를 호출하는데 있어서
오버헤드가 적다고 나와있다.
그렇다면 함수를 재사용할때 변동되지 않는 인자를 디폴트인자로 설정해 놓는다면 그만큼 넘겨야되는 값이 적기 때문에 효율적이게 될 것이다.
이제 디폴트 인자를 사용하는 예를 살펴보자.
#include "stdafx.h" #includeusing namespace std; enum INT_TYPE{ DECIMAL, OCTAL, HEXADECIMAL, }; void PrintArray(const int arr[], int size = 5, INT_TYPE type = DECIMAL); int _tmain(int argc, _TCHAR* argv[]) { int arr1[] ={10, 20, 30, 40, 50}; int arr2[] ={10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; //디폴트 인자는 오른쪽 인자부터 지정한다. PrintArray(arr1); PrintArray(arr1, 5, HEXADECIMAL); PrintArray(arr2); PrintArray(arr2, 10); return 0; } void PrintArray(const int arr[], int size , INT_TYPE type ){ cout.setf(ios::showbase); //일단은 정수를 출력할 때 진법 정보를 함께 출력하는 기능! for(int i=0; i<size; i++) { switch(type) { case DECIMAL: cout << dec; break; case OCTAL: cout << oct; break; case HEXADECIMAL: cout << hex; break; } cout.width(5); cout << arr[i] <<" "; } cout << endl; }
댓글 없음:
댓글 쓰기