Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1086503
  • 博文数量: 254
  • 博客积分: 10185
  • 博客等级: 上将
  • 技术积分: 2722
  • 用 户 组: 普通用户
  • 注册时间: 2007-07-25 15:04
文章存档

2011年(8)

2009年(1)

2008年(31)

2007年(214)

分类: 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";        //被减串可以是ab或者c

        cout << "字符串a - \"d\" = ";       //为了能输出"d",所以加\进行转义

        c.show();

        a.show_num();

}

运行结果为:

字符串a = abcdef

字符串b = def

字符串a + b = abcdefdef

字符串a - "d" = abcef

共删除字符数:1

阅读(566) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~