Minwoo Dev.

[C++] 윤성우의 열혈 C++ 프로그래밍 Ch01-3 : 매개변수의 디폴트 값 본문

C++

[C++] 윤성우의 열혈 C++ 프로그래밍 Ch01-3 : 매개변수의 디폴트 값

itisminu 2024. 3. 2. 17:26
728x90
반응형
SMALL

 

문제 1

예제 DefaultValue3.cpp에 정의된 함수 BoxVolume를 '매개변수의 디폴트 값 지정' 형태가 아닌, '함수 오버로딩'의 형태로 재 구현해보자. 물론 main 함수는 변경하지 않아야 하며, 실행결과도 동일해야 한다.

 

DefaultValue3.cpp

#include <iostream>

int BoxVolume(int length, int width = 1, int height = 1);

int main(void)
{
    std::cout << "[3,3,3] : " << BoxVolume(3, 3, 3) << std::endl;
    std::cout << "[5,5,D] : " << BoxVolume(5, 5) << std::endl;
    std::cout << "[7,D,D] : " << BoxVolume(7) << std::endl;
    // std::cout << "[D,D,D] : " << BoxVolume() << std::endl;

    return 0;
}

int BoxVolume(int length, int width, int height)
{
    return length * width * height;
}

 

 

 

 

정답

 

#include <iostream>

int BoxVolume(int length)
{
    int width = 1;
    int height = 1;
    return length * width * height;
}

int BoxVolume(int length, int width)
{
    int height = 1;
    return length * width * height;
}

int BoxVolume(int length, int width, int height)
{
    return length * width * height;
}

int main(void)
{
    std::cout << "[3,3,3] : " << BoxVolume(3, 3, 3) << std::endl;
    std::cout << "[5,5,D] : " << BoxVolume(5, 5) << std::endl;
    std::cout << "[7,D,D] : " << BoxVolume(7) << std::endl;
    // std::cout << "[D,D,D] : " << BoxVolume() << std::endl;

    return 0;
}

 

 

 

 

 

 

 

 

문제 2

다음과 같은 형태로의 함수 오버로딩은 문제가 있다. 어떠한 문제가 있는지 설명해보자.

int SimpleFunc(int a=10){
    return a+1;
}

int SimpleFunc(void){
    return 10;
}

 

정답

 

매개변수가 없이 SimpleFinc()로 함수를 호출한다면 매개변수를 아무것도 없는 void 상태로 판단할지, 디폴트값으로 a=10을 넣어 11을 반환할지 컴퓨터가 판단하지 못한다.

한마디로 매개변수가 아무것도 없이 함수가 호출될 때 두 함수 모두 실행될 수 있기에 에러가 발생한다.

 

728x90
반응형
LIST