分类: C/C++
2007-07-25 16:16:48
下面的类MyString提供了重载字符串加法“ + ”(两个字符串的连接)、字符串与单个字符的减法“ - ”(从字符串中去掉某个字符)及统计删除的字符个数的功能。
#include "stdafx.h"
#include "string.h"
#include "iostream.h"
class MyString
{
char p[30]; // 说明了一个存放字符串的字符数组
int num; // 用来统计删去的字符个数
public :
MyString operator + (MyString str1) //重载运算符" + "
{
MyString temp;
strcpy(temp.p,p);
strcat(temp.p, str1.p);
return temp;
}
MyString operator - (MyString str1) //重载运算符" - "
{
MyString temp;
strcpy(temp.p, p);
int i = 0;
while(temp.p[i] != '\0')
{
if(temp.p[i] == str1.p[0])
{
for(int k = i;temp.p[k] != '\0';k ++)
{
temp.p[k] = temp.p[k+1];
}
num ++; //对对象本身中的num++
i --;
}
i ++;
}
temp.num = num; //对象本身的num赋值给temp对象的num
return temp;
}
void show()
{
cout << p << endl;
}
void show_num()
{
cout << "共删除字符数:"<< num << endl;
}
MyString (char s1[])
{
num = 0;
strcpy(p, s1);
}
MyString ()
{
num = 0;
}
};
//下面给出使用重载后运算符的一个主函数:
void main(int argc, char* argv[])
{
MyString a("abcdef"),b("def");
MyString c;
cout << "字符串a = ";
a.show();
cout << "字符串b = ";
b.show();
c = a + b;
cout << "字符串a + b = ";
c.show();
c = a - "d"; //被减串可以是a、b或者c
cout << "字符串a - \"d\" = "; //为了能输出"d",所以加\进行转义
c.show();
a.show_num();
}
运行结果为:
字符串a = abcdef 字符串b = def 字符串a + b = abcdefdef 字符串a - "d" = abcef 共删除字符数:1 |