自己定义mystring类实现string功能
#include <iostream>
#include<cstring>
using namespace std;
class myString
{
private:
char *str; //记录c风格的字符串
int size; //记录字符串的实际长度
public:
//无参构造
myString():size(10)
{
str = new char[size]; //构造出一个长度为10的字符串
strcpy(str,"");
}
//有参构造
myString(const char *s)
{
size = strlen(s);
str = new char[size+1];
strcpy(str, s);
}
//拷贝构造
myString(myString &m)
{
size=strlen(m.str);
str=new char[size+1];
strcpy(str,m.str);
cout<<"拷贝构造函数"<<endl;
}
//析构函数
~myString()
{
delete [] str;
cout<<"析构函数"<<endl;
}
//判空函数
int myempty()
{
if(!strcmp(str,""))
return 0;
return true;
}
//size函数
int mysize()
{
return strlen(str);
}
//c_str函数
char* &myc_str()
{
return str;
}
//at函数
char &at(int pos)
{
int l=strlen(str);
if(pos>l)
{
cout<<"pos超出范围"<<endl;
}
return str[pos];
}
};
int main()
{
myString s1("1234");
cout<<"s1= "<<s1.myc_str()<<endl;
myString s2=s1;
cout<<"s2= "<<s2.myc_str()<<endl;
cout<<"length= "<<s2.mysize()<<endl;
if(!s2.myempty())
cout<<"字符串为空"<<endl;
else
cout<<"字符串不为空"<<endl;
cout<<"s2[1]="<<s2.at(1)<<endl;
}