#include <iostream>
#include <string.h>
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);
cout<<"mystring::有参构造 str = "<<str<<" this = "<<this<<endl;
}
//拷贝构造
mystring(const mystring &other):str(new char(*(other.str))),size(other.size)
{
strcpy(this->str,other.str); //拷贝字符串
this->size = other.size; //拷贝字符串长度
cout<<"mystring::拷贝构造 str = "<<str<<" this = "<<this<<endl;
}
//拷贝赋值
mystring & operator=(const mystring &other)
{
if(this != &other)
{
strcpy(this->str,other.str);
this->size = other.size;
}
cout<<"mystring::拷贝赋值函数 str = "<<str<<" this = "<<this<<endl;
return *this;
}
//析构函数
~mystring()
{
delete str;
cout<<"mystring::析构函数 this = "<<this<<endl;
}
//判空函数
bool empty()
{
return 0==size;
}
//size函数
int mystring_size()
{
return strlen(str);
}
//at函数
char &at(int pos)
{
return str[pos-1];
}
//c_str函数
const char *c_str()
{
return this->str;
}
};
int main()
{
mystring m1("hello");
mystring m2(m1);
mystring m3;
m3 = m2;
cout<<m1.empty()<<endl;
cout<<"字符串长度为:"<<m1.mystring_size()<<endl;
cout<<"at(1) = "<<m1.at(1)<<endl;
cout<<"c_str:"<<m1.c_str()<<endl;
return 0;
}
运行结果: