使用C+;中的相同定义重载函数+; 我知道通过使用不同的参数和定义,C++中函数重载的过程。然而,如果我有两个函数,除了它们的参数外,它们是相同的,那么有一种方法可以只定义一次
我使用的功能是检查输入是否正确(即输入的是数字而不是字符)。一个用于int,另一个用于float。由于这一点以及我通过引用传递变量的事实,定义是完全相同的 这两个函数声明如下:使用C+;中的相同定义重载函数+; 我知道通过使用不同的参数和定义,C++中函数重载的过程。然而,如果我有两个函数,除了它们的参数外,它们是相同的,那么有一种方法可以只定义一次,c++,overloading,definitions,C++,Overloading,Definitions,我使用的功能是检查输入是否正确(即输入的是数字而不是字符)。一个用于int,另一个用于float。由于这一点以及我通过引用传递变量的事实,定义是完全相同的 这两个函数声明如下: void Input (float &Ref); void Input (int &Ref); 然后,他们共享以下共同定义: Function_Header { static int FirstRun = 0; // de
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";
}
}
Function\u头
{
static int FirstRun=0;//将第一次运行声明为0(false)
如果(FirstRun++)//在检查为true后递增first run,这将导致仅在第一次运行时丢失该值。
{//第一次运行后,需要清除任何以前的输入剩余(即,如果用户输入“10V”)
//在此之前,需要清除“V”。
std::cin.clear();//清除错误标志
std::cin.ignore(INT_MAX,'\n');//放弃该行
}
while(!(std::cin>>Ref))//收集输入并检查其是否为有效输入(即数字)
{//如果输入不正确,请清除输入并请求重新输入,循环直到用户输入正确。
std::cin.clear();//清除错误标志
std::cin.ignore(INT_MAX,'\n');//放弃该行
std::cout最好(也是唯一?)的解决方案是使用模板模板很有用:
template <typename T>
void Input (T &Ref)
{
...
}
std::string s;
int i;
float f;
Input(s);
Input(i);
Input(f);
模板
无效输入(T&Ref)
{
...
}
std::字符串s;
int i;
浮动f;
输入;
输入(i);
输入(f);
模板
无效输入(T&ref)
{
..
}
使用函数模板?非常感谢,我以前没有听说过模板,但在cplupus.com上看到的解释正是我想要的。你使用了“模板”和另一个答案使用了“模板”有什么区别吗?在这方面没有任何区别。我个人更喜欢使用typename
。
template<class T>
void Input(T& ref)
{
..
}