实现自己的英文单词MyWord类

实现自己的英文单词MyWord类,为该类提供各种功能(加法、流插入、流提取、查找、替换)

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cassert>
using namespace std;

class Myword
{
    
    
    
    public:
    char *pdata;
    int length;
    Myword(char *pw="",int size=0)
    {
    
    
        length=size;
        pdata=new char[length+1];
        strcpy(pdata,pw);
        assert(pdata!=NULL);
        pdata[length+1]='\0';
    }
    ~Myword()
    {
    
    
        if(pdata!=NULL)
        {
    
    
            pdata=NULL;
        }
    }
};
    Myword operator+(Myword &a,Myword &b) //加法
    {
    
    
        Myword temp;
        temp.length=a.length+b.length;
        temp.pdata=new char [temp.length+1];
        assert(temp.pdata!=NULL);
        strcpy(temp.pdata,a.pdata);
        strcat(temp.pdata,b.pdata);
        temp.pdata[temp.length+1]='\0';
        return temp;
    }
    istream & operator >> (istream & is , Myword & rhs)  // >> cin
    {
    
    
         is>>rhs.length>>rhs.pdata;
         return (is);
    }
    ostream& operator<<(ostream &cout,const Myword &n)//cout
    {
    
    
        cout<<n.pdata<<'\t'<<n.length<<endl;
        return cout;
    }

    void find(const Myword &a,const Myword &b,const Myword &c,const Myword &d)
    {
    
    
        if(strcmp(a.pdata,d.pdata)==0||strcmp(b.pdata,d.pdata)==0||strcmp(c.pdata,d.pdata)==0)
        {
    
    
            cout<<"found it !"<<endl;
        }
        else 
        cout<<"not found!"<<endl;
       
    }
    void replace(Myword &a,Myword &b)//用y替换x
    {
    
    
        a.length=b.length;
        a.pdata=new char[a.length+1];
        assert(a.pdata!=NULL);
        strcpy(a.pdata,b.pdata);
        a.pdata[a.length+1]='\0';
    }
    

int main()
{
    
       
    Myword a("Hell0",5);
    Myword b("World",5);
    cout<<"a="<<a<<endl;
    cout<<"b="<<b<<endl;
    Myword c;
    c=a+b;
    cout<<"c="<<c<<endl;
    Myword d;
    cin>>d;
    cout<<"d="<<d<<endl;
    find(a,b,c,d);
    replace(a,b);
    cout<<"a="<<a<<endl;
    cout<<"b="<<b<<endl;
}

运行结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/suxuanxuan/article/details/109560649
今日推荐