实现C++中对string类的封装
string类型,是C++对C基础类型的封装实现的,用法可以类比于基础类型int ,char ,并且实现字符串直接的=(赋值),>,<,==,及[ ]运算。
今天我试着自己封装了String类型。并对运算符进行重载,实现了类似于基础类型的String的关系运算。
<pre style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size:18px;"><span style=" color:#000080;">#ifndef</span><span style=" color:#c0c0c0;"> </span>MYSTRING_H</span>
#define MYSTRING_H
#include <stdlib.h>
class MyString
{
public:
MyString(const char *str=NULL); //带默认参数的构造器
char *c_ret();
~MyString();
MyString *operator=(const MyString &another);//对赋值号的重载
MyString operator+(const MyString & other);//对加号重载
bool operator==(const MyString &other);//对等号重载
bool operator>(const MyString &other);//对大于号重载
bool operator<(const MyString &other);//对小于号重载
char operator[](int idx); //对取下标重载
private:
char *_str;
};
#endif // MYSTRING_H
<pre style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size:18px;"><span style=" color:#000080;">#include</span><span style=" color:#c0c0c0;"> </span><span style=" color:#008000;">"mystring.h"</span></span>
#include <iostream>
#include <string.h>
MyString::MyString(const char *str)
{
if(str==NULL)
{
_str=new char[1];
*_str='\0';
}
else
{
int len =strlen(str);
_str=new char[len+1];
strcpy(_str,str);
}
}
char *MyString::c_ret()
{
return _str;
}
MyString::~MyString()
{
delete []_str;
}
MyString &MyString::operator=(const MyString &another) //返回MyString的引用,也可以返回this指针,用MyString *作返回值。可以实现连等即 a=b=c;
{
if(this ->_str==another._str) //如果为赋值号左右判断为相同的对象,则直接返回this指针。
return this;
else
{
delete _str;
int len=strlen(another._str);
_str=new char[len+1];
strcpy(_str,another._str);
return *this;
}
}
MyString MyString::operator+(const MyString &other)
{
using std::cout;
using std::endl;
MyString *p=new MyString;
int len1=strlen(_str);
int len2=strlen(other._str);
p->_str=new char[len1+len2+1];
memset(p->_str,0,len1+len2+1);
strcat(p->_str,_str);
strcat(p->_str,other._str);
return *p;
}
bool MyString::operator==(const MyString &other)
{
if(strcmp(_str,other._str)==0)
return true;
else
return false;
}
bool MyString::operator>(const MyString &other)
{
if(strcmp(_str,other._str)>0)
return true;
else
return false;
}
bool MyString::operator<(const MyString &other)
{
if(strcmp(_str,other._str)<0)
return true;
else
return false;
}
char MyString::operator[](int idx)
{
return this->_str[idx];
}
#include <iostream>
#include <mystring.h>
using namespace std;
int main()
{
MyString m1("malian");
MyString m2("majingjing");
MyString m3=m1+m2;
cout<<m3.c_ret()<<endl;
MyString m4("hahahaha");
m4=m3;
cout<<"test"<<m4.c_ret()<<endl;
MyString m5("hahah");
if(m4==m5)
cout<<"yes"<<endl;
else if(m4>m5)
cout<<"大于"<<endl;
else if(m4<m5)
cout<<"小于"<<endl;
cout<<m4[1]<<endl;
return 0;
}