设为首页 加入收藏

TOP

1.2.1 运算符重载的定义
2013-10-07 00:17:23 来源: 作者: 【 】 浏览:70
Tags:1.2.1 运算 重载 定义

1.2  运算符重载

1.2.1  运算符重载的定义

C++(www.cppentry.com)提供了许多库函数,如字符串操作库函数、数学运算库函数和图形操作库函数等。同时也提供了许多标准运算符,如+、-、*、/、&等。这些运算符就像C++(www.cppentry.com)的库函数一样,实现一定的功能,是程序开发的基本工具。

对于库函数,通过1.1节的学习,已经能够对其进行重载。示例1.4是重载库函数strcat()的示例,实现字符串的连接功能。

示例清单1.4

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

//char *strcat( char *strDestination, const char *strSource )是C++(www.cppentry.com)声明的库函数原型

//下面重载strcat()
/*************************************************************
 功能:   连接两个字符串
 strDestination: 目标字符串 
strSource: 源字符串 
DestLength:  限制目标字符串的最大长度,避免目标数组越界
返回值:  目标字符串的最后长度 
**************************************************************/
int strcat(char *strDestination, const char *strSource,unsigned int DestLength)
{
//如果目标字符串数组已经填满,不进行连接,返回当前长度
if(strlen(strDestination)<DestLength)   //设strSource的长度在DestLength的要求范围内
strncpy(strDestination+strlen(strDestination),strSource,DestLength-strlen(strDestination));
printf("%s\n",strDestination);
return strlen(strDestination);   //返回目标字符串的最后长度
}

#define DEST_MAXLEN 40
int main(int argc, char* argv[])
{
char str[DEST_MAXLEN];
strcpy(str,"strcat ");
//调用C++(www.cppentry.com)库函数
printf("%s\n",strcat(str," C++(www.cppentry.com) runtime function")); 
strcpy(str,"strcat ");
//调用重载函数
printf("destination string length is %d\n",
strcat(str,"override function", DEST_MAXLEN));

return 0;
}

程序输出结果:
 strcat  C++(www.cppentry.com) run time function
strcat  override function
destination string length is 26

同样,对于运算符,C++(www.cppentry.com)也为我们提供了重载的机会。运算符重载就是运用函数重载的方法,对C++(www.cppentry.com)提供的标准运算符重新定义,完成某种特定的操作。
【责任编辑:夏书 TEL:(010)68476606】

回书目   上一节   下一节

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇1.2.2 运算符重载的特点 下一篇1.2.4 operator调用形式

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: