使用C中相同的定义重载函数
发布时间:2020-12-16 09:48:00 所属栏目:百科 来源:网络整理
导读:我通过使用不同的参数和定义了解C中函数重载的过程.但是,如果我有两个与它们的参数相同的函数,那么有一种方法只能有一次这个定义. 我使用的功能是检查输入是否正确(即输入的字符不是字符).一个是int,另一个是float.由于这一点以及我通过引用传递变量的事实,
我通过使用不同的参数和定义了解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:ttttt"; } } 如果有一种方法必须有相同代码的两个相同副本,而它仍然用于两种参数类型,那么我可以显着缩短我的程序的代码.我确定我不是唯一有这个问题的人,但我所有的搜索都是关于如何使用多个定义重载函数的解释. 任何帮助或建议将不胜感激. 解决方法
模板很有用:
template <typename T> void Input (T &Ref) { ... } std::string s; int i; float f; Input(s); Input(i); Input(f); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |