다른 매개 변수와 정의를 사용하여 C++에서 함수 오버로딩 프로세스를 알고 있습니다. 그러나 그들의 매개 변수와 별개로 두 개의 함수가 있다면이 정의를 한 번만 가질 수있는 방법이 있습니다.C++에서 동일한 정의를 사용하여 함수 오버로드
내가 사용한 기능은 올바른 입력 (즉, 문자가 입력되지 않은 숫자)을 확인하는 것입니다. 하나는 int이고 다른 하나는 float입니다. 이 사실과 제가 참조로 변수를 전달한다는 사실은 정의가 정확히 동일합니다.
void Input (float &Ref);
void Input (int &Ref);
그리고 그들은 다음의 일반적인 정의를 공유 :
선언으로하는 두 가지 기능
다음Function_Header
{
static int FirstRun = 0; // declare first run as 0 (false)
if (FirstRun++) // increment first run after checking for true, this causes this to be missed on first run only.
{ //After first run it is required to clear any previous inputs leftover (i.e. if user entered "10V"
// previously then the "V" would need to be cleared.
std::cin.clear(); // clear the error flags
std::cin.ignore(INT_MAX, '\n'); // discard the row
}
while (!(std::cin >> Ref)) // collect input and check it is a valid input (i.e. a number)
{ // if incorrect entry clear the input and request re-entry, loop untill correct user entry.
std::cin.clear(); // clear the error flags
std::cin.ignore(INT_MAX, '\n'); // discard the row
std::cout << "Invalid input! Try again:\t\t\t\t\t";
}
}
방법은 주위에 같은 두 개의 동일한 사본을 할 필요가 있었다면 두 매개 변수 유형에 여전히 사용되는 동안 코드를 상당히 단축 할 수 있습니다. 이 문제가있는 유일한 사람은 아니지만 모든 검색은 여러 정의를 사용하여 함수를 오버로드하는 방법에 대한 설명입니다.
도움이나 조언을 주시면 감사하겠습니다.
사용 기능 템플릿? – taocp