仿照string类,实现myString类
class myString
{
private:
char *str; //记录c风格的字符串
int size; //记录字符串的实际长度
public:
//无参构造
myString():size(10)
{
str = new char[size]; //构造出一个长度为10的字符串
strcpy(str,“”);
}
//有参构造
myString(const char *s) //string s(“hello world”)
{
size = strlen(s);
str = new char[size+1];
strcpy(str, s);
}
//拷贝构造
//析构函数
//判空函数
//size函数
//c_str函数
//at函数
char &at(int pos)
};
#include <iostream>
#include<cstring>
using namespace std;
class mystring;
class mystring
{
char *str;
int size;
public:
mystring():size(10)//无参构造
{
str=new char[size];
strcpy(str,"");
}
mystring(const char *s)//有参构造
{
size=strlen(s);
str=new char[size+1];
strcpy(str,s);
}
//拷贝构造
mystring(const mystring &other):str(other.str),size(other.size)
{
str=new char[other.size];
strcpy(str,other.str);
cout<<""<<str<<endl;
}
//析构函数
~mystring()
{
delete str;
cout<<"mystring::析构函数,this="<<this<<endl;
}
//判空函数
bool empty()
{
if(sizeof(str)==0)
{
cout<<"空"<<endl;
return 0;
}
return 0;
}
//size函数
int mystring_size()
{
cout<<""<<size<<endl;
return size;
}
//c_str函数
//at函数
char &at(int pos)
{
if(pos<0||pos>=size)
{
cout<<"错误"<<endl;
}
char &a=str[pos];
return a;
}
};
int main()
{
mystring s1("hello");
mystring s2(s1);
s2.mystring_size();
cout<<""<<s2.at(1)<<endl;
return 0;
}