在C++中,string是一种常用的类,相较于C语言的字符数组和字符串指针,string对于字符串的操作更加简单。
1.定义Mystring类
#include <iostream>
#include <cstring>
#include <cassert>
using namespace std;
class Mystring{
public:
Mystring()//默认构造函数
{
data=new char [1];
*data='\0';
}
Mystring(const char *s)//构造函数有参数
{
//如果有字符串,则创建比字符串大一个的空间,并复制给类成员变量
int len;
len = strlen(s);
data=new char[len+1];
assert(NULL != data);
strcpy(data,s);
}
Mystring(const Mystring &my)//拷贝构造函数
{
int len;
len = strlen(my.data);
data=new char[len+1];
assert(NULL != my.data);
strcpy(data,my.data);
}
~Mystring()//析构函数
{
delete [] data;
}
public:
char getval()
{
return *data;
}
bool operator ==(const Mystring &);
Mystring & operator =(const Mystring &);
Mystring & operator +(const Mystring &);
friend ostream & operator <<(ostream &,Mystring &);
friend istream & operator >>(istream &,Mystring &);
private:
char *data;
};
2.类操作
//输出流运算符重载
ostream & operator <<(ostream &os,Mystring &my)
{
os << my.data;
return os;
}
//输入流运算符重载
istream & operator >>(istream &os,Mystring &my)
{
os >> my.data;
return os;
}
//==运算符重载
bool Mystring::operator ==(const Mystring &my)
{
if(0 == strcmp(this->data,my.data))
return true;
else
return false;
}
//=运算符重载
Mystring & Mystring::operator =(const Mystring &my)
{
if(*this == my)
return *this;
delete this->data;
int len;
len = strlen(my.data);
this->data=new char[len+1];
strcpy(this->data,my.data);
return *this;
}
//+运算符重载
Mystring & Mystring::operator +(const Mystring &my)
{
int len;
char *temp;
len = strlen(this->data)+strlen(my.data);
temp = new char [len+1];
assert(NULL != temp);
strcpy(temp,this->data);
strcat(temp,my.data);
delete this->data;
this->data = temp;
return *this;
}
3.测验
int main()
{
Mystring a="hello";
Mystring b;
b=a;
cout << "a:"<< a << endl;
cout << "b:"<< b << endl;
cout <<"a+b:"<<(a+b)<<endl;
cout <<"a?=b:"<<(a==b)<<endl;
Mystring c;
cout<<"c:";
cin>>c;
cout<<"b+c:"<<(b+c)<<endl;
return 0;
}
输出结果: