c++运算符重载与string一些函数的实现

1.。。h文件

#ifndef _MYSTRING_H
#define _MYSTRING_H
#include<iostream>
using namespace std;

class MyString
{
    friend ostream &operator<<(ostream &out,const MyString &m);
    friend istream &operator>>(istream &in, MyString &m);
private:
    char *m_data;
    int m_len;
public:
    MyString();
    MyString(char *str);
    MyString(int l,char ch);
    MyString(const MyString &s);
    MyString operator=(MyString &m);

};


#endif
 

2.。。cpp文件

#include<iostream>
#include<string.h>
#include"MyString.h"
using namespace std;
MyString::MyString()
{
    m_data=new char;
    m_len=1;
}
MyString::MyString(char *str)
{
    m_len=strlen(str);
    m_data=new char[m_len+1];
    strcpy(m_data,str);
    
}
MyString::MyString(int l,char ch)
{
    m_len=l;
    m_data=new char[m_len+1];
    for(int i=0;i<l;i++)
    {
        m_data[i]=ch;
    }
    m_data[l]='\0';
    
}

MyString::MyString(const MyString &s)
{
    m_len=s.m_len;
    m_data=new char[m_len+1];
    stpcpy(m_data,s.m_data);
    
}
MyString MyString::operator=(MyString &m)
{
    m_data=m.m_data;
    m_len=m.m_len;
}
ostream &operator<<(ostream &out,const MyString &m)
{
    out<<m.m_data<<endl;
    return out;
}
istream &operator>>(istream &in, MyString &m)
{
    char tmp[1024]={0};
    in>>tmp;
    if(m.m_data!=NULL)
    {
        delete m.m_data;
    }
    m.m_len=strlen(tmp);
    m.m_data=new char[m.m_len+1];
    strcpy(m.m_data,tmp);
    return in;
}
int main()
{
    MyString s1;
    MyString s2("hello world");
    MyString s3(10,'a');
    MyString s4=s2;
    MyString s5(s2);
    
    cout<<s1<<endl;
    cout<<s2<<endl;
    cout<<s3<<endl;
    cout<<s4<<endl;
    cout<<s5<<endl;
    
    cin>>s1;
    cout<<s1<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sinat_42721727/article/details/81227578