封装mystring类
#include <iostream>
#include <cstring>
using namespace std;
class myString;
class myString
{
public:
//无参构造
myString() ;
//有参构造
myString(const char *s);
//拷贝构造
myString( const myString &other) ;
//析构构造
~myString();
//判空函数
bool myempty();
//size函数
int mysize();
//c_str函数
const char* myc_str();
//at函数
char my_at(int n);
//输出字符串函数
void show();
private:
int size;
char *str;
};
int main()
{
myString s1("hello world");
cout<<"字符串s1:"<<endl;
s1.show();
myString s2(s1);
cout<<"字符串s2:"<<endl;
s2.show();
char ch[20] ;
strcpy(ch,s1.myc_str());
cout<<"ch = "<<ch<<endl;
cout<<"s1.my_at[1] : "<<s1.my_at(1)<<endl;
cout<<"s1.my_at[13] : "<<s1.my_at(13)<<endl;
return 0;
}
//无参构造
myString::myString():size(20)
{
str = new char[size];
strcpy(str,"");
}
//有参构造
myString::myString(const char *s)
{
size = strlen(s);
str = new char[size+1];
strcpy(str,s);
//cout<<"stu::有参构造,this = "<<this<<endl;
}
//拷贝构造
myString::myString( const myString &other): size(other.size),str(new char[size+1]{*(other.str)})
{
strcpy(str,other.str);
//cout<<"stu::拷贝构造,this = "<<this<<endl;
}
//析构构造
myString::~myString()
{
delete []str;
//cout<<"stu::析构函数,this = "<<this<<endl;
}
//判空函数
bool myString::myempty()
{
return strlen(str);
}
//size函数
int myString::mysize()
{
return strlen(str);
}
//c_str函数
const char* myString::myc_str()
{
return str;
}
//at函数
char myString::my_at(int n)
{
if(n < 0||n >size)
{
cout<<"越界"<<endl;
return '\0';
}
return str[n];
}
//输出字符串函数
void myString::show()
{
cout<<"size = "<<size<<endl;
cout<<"str = "<<str<<endl;
}