代码
#include <iostream>
#include <cstring>
using namespace std;
class My_string
{
private:
char* cstr;
int len;
public:
My_string():cstr(NULL),len(0) //无参构造
{
}
My_string(const char* str) //有参构造
{
this->len = strlen(str);
this->cstr = new char[(this->len)+1];
strcpy(this->cstr,str);
}
My_string(const My_string &other)//拷贝构造函数
{
this->len = other.len;
this->cstr = new char;
strcpy(this->cstr,other.cstr);
}
~My_string() //析构函数
{
delete this->cstr;
}
bool empty() //判断是否为空
{
return this->len == 0 ? true : false;
}
int size() //返回字符串的长度
{
return this->len;
}
char &at(int index) //定位函数
{
return *(this->cstr+index);
}
char* c_str() //转化为C风格的字符串
{
return this->cstr;
}
};
int main()
{
My_string s1 = "hello";
//e 0 5 hello
cout << s1.at(1) << " " << s1.empty() << " " << s1.size() << " " << s1.c_str() << endl;
My_string s2(s1);
//hello
cout << s2.c_str() << endl;
My_string s3;
//1
cout << s3.empty() <<endl;
My_string* s4 = new My_string(s1);
//hello 0
cout << s4->c_str() << " " << s4->empty() << endl;
delete s4;
//e 0 5 hello
cout << s1.at(1) << " " << s1.empty() << " " << s1.size() << " " << s1.c_str() << endl;
return 0;
}
图片