函数重载详解(C++)

Eddy 发布于2011-4-17 14:12:1 分类: 技术心得 已浏览loading 网友评论0条 我要评论

实际编程中,通常将一组功能相近的函数定义为重载函数。一组重载函数是以参数类型或参数个数加以区别的。函数的返回值对区别重载函数没有意义。每个重载函数可以有不同的返回类型。

下面列举三种情况下重载函数使用实例。

全局范围内定义重载函数:

#include "stdio.h"
#include "string.h"

//全局范围内定义两个重载函数
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,Caption=%d\n",Text,Type);
}

int main()
{
 //调用函数
 ShowMessage("ok","welcome");
 ShowMessage("ok",1);
 
 return 0;
}

类中定义重载函数:

#include "stdio.h"
#include "string.h"

class CMessage
{
public:
 CMessage(){};
 //类中定义两个内联的重载函数
 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,Caption=%d\n",Text,Type);
 }
};

int main()
{
 CMessage LoginMessage;
 //依次调用重载的成员函数
 LoginMessage.ShowMessage("ok","welcome");
 LoginMessage.ShowMessage("ok",1);
 
 return 0;
}

父类和子类中定义重载函数:

#include "stdio.h"
#include "string.h"
class CMessage
{
public:
    CMessage(){};
 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);
 }
    void ShowMessage(const char* Text)
 {
 printf("Message: Text=%s\n",Text);
 }

};

class COKMessage :public CMessage
{
public:
    COKMessage(){};
 void ShowMessage(const char* Text ,const char* Caption)
 {
     char TextForOK[40];
  strcpy(TextForOK,"OK,");
  strcat(TextForOK,Text);
    CMessage::ShowMessage( TextForOK , Caption); 
 }
    void ShowMessage(const char* Text ,unsigned int Type)
 {
  char TextForOK[40];
  strcpy(TextForOK,"OK,");
  strcat(TextForOK,Text);
    CMessage::ShowMessage(TextForOK , Type); 
 
 }
    void ShowMessage(const char* Text )
 {
  char TextForOK[40];
  strcpy(TextForOK,"OK,");
  strcat(TextForOK,Text);
    CMessage::ShowMessage(TextForOK); 
 }

};
int main()
{
 COKMessage OKMessage;
 OKMessage.ShowMessage("Welcom");
 OKMessage.CMessage::ShowMessage("Welcom");

 return 0;
}

已经有(0)位网友发表了评论,你也评一评吧!
原创文章如转载,请注明:转载自Eddy Blog
原文地址:http://www.rrgod.com/technique/759.html     欢迎订阅Eddy Blog

关于 函数  重载  详解  C  的相关文章

记住我的信息,下次不用再输入 欢迎给Eddy Blog留言