|
1.1.3 重载函数使用实例
在全局和类的范围内都可以定义重载函数。示例1.1和示例1.2分别演示了在全局范围内和类的范围内定义重载函数,两个程序的输出结果相同。
示例清单1.1
#include "stdio.h" //在全局范围内定义两个ShowMessage()重载函数 void ShowMessage(const char* Text ,const char* Caption) { printf("Message: Text=%s,Caption=%s\n",Text,Caption); }
void ShowMessage(const char* Text ,unsigned int Type) { printf("Message: Text=%s,Type=%d\n",Text,Type); }
int main() { //依次调用两个重载函数 ShowMessage("ok","welcom"); ShowMessage("ok",1);
return 0; } | 示例清单1.2
#include "stdio.h" class CMessage { public: CMessage(){}; //在类中定义两个内联的重载函数ShowMessage() void ShowMessage(const char* Text ,const char* Caption) { printf("Message: Text=%s,Caption=%s\n",Text,Caption); } void ShowMessage(const char* Text ,unsigned int Type) { printf("Message: Text=%s,Type=%d\n",Text,Type); }
};
int main() { CMessage LoginMessage; //依次调用对象LoginMessage的两个重载的成员函数 LoginMessage.ShowMessage("ok","welcom"); LoginMessage.ShowMessage("ok",1);
return 0; } | 以上两程序的输出结果如下:
Message: Text=ok,Caption=welcom Message: Text=ok,Type=1
| 通过以上学习,可以得出这样的结论:编译器依据传递的实参类型和个数确定重载函数的调用。【责任编辑: 夏书 TEL:(010)68476606】
|