mystring.h
#ifndef MYSTRING_H
#define MYSTRING_H
#include<iostream>
using namespace std;
class mystring
{
char * _str;
public:
mystring(const char*str=nullptr);
mystring(const mystring &another);
mystring &operator=(const mystring&another);
mystring operator+(const mystring&another);
char& operator[](const int& i);
bool operator==(const mystring&another);
bool operator<(const mystring &another);
bool operator>(const mystring &another);
//返回引用是为了能够连续输出,如果不使用引用则只能一个一个输出(因为是一个右值)
friend ostream &operator<<(ostream&out,mystring&str);
int size();
~mystring();
};
mystring.cpp
#include "mystring.h"
#include<string.h>
int mystring::size(){
return strlen(this->_str);
}
mystring::mystring (const char* str){
if(str==nullptr)
{
_str=new char[1];
_str[0]='\0';
return;
}
_str=new char[strlen(str)+1];
strcpy(_str,str);
}
mystring::mystring(const mystring &another){
int lenth=strlen(another._str);
_str=new char[lenth+1];
strcpy(_str,another._str);
}
mystring& mystring::operator=( const mystring&another){
if(*this==another)return *this;
else {
delete[] _str;
int lenth=strlen(another._str);
_str=new char[lenth+1];
strcpy(_str,another._str);
return *this;
}
}
mystring mystring:: operator+(const mystring&another){
mystring tmp;
delete[] tmp._str;
int lenth=strlen(_str)+strlen(another._str);
tmp._str=new char[lenth+1];
memset(tmp._str,0,lenth);
strcat(tmp._str,_str);
strcat(tmp._str,another._str);
return tmp;
}
char& mystring:: operator[](const int& i){
return _str[i];
}
bool mystring:: operator==(const mystring&another){
if( strcmp(_str,another._str)==0)
return true;
else return false;
}
bool mystring:: operator<(const mystring &another){
if( strcmp(_str,another._str)<0)
return true;
else return false;
}
bool mystring:: operator>(const mystring &another){
if( strcmp(_str,another._str)>0)
return true;
else return false;
}
ostream & operator<<(ostream&out,mystring&str){
for(int i=0;i<strlen(str._str);++i)
out<<str._str[i];
return out;
}
mystring:: ~mystring(){
delete[]_str;
}
main函数测试
#include<iostream>
#include<mystring.h>
#include<string>
using namespace std;
int main(){
mystring test1("hello");
cout<<test1<<endl;
cout<<test1[0]<<endl;
mystring test2("world");
cout<<test2<<endl;
mystring test3=test1+test2;
cout<<test3<<endl;
if(test1>test2)
cout<<test1<<" > "<<test2<<endl;
else if(test1==test2) cout<<test1<<" = "<<test2<<endl;
else cout<<test1<<" < "<<test2<<endl;
return 1;
}
测试结果: