string
#include <iostream>
#include <cstring>
using namespace std;
class my_string
{
private:
char *str;
int len;
public:
//无参构造
my_string()
{
len = 10;
str = new char[len];
}
//有参构造
my_string(char *p)
{
len = strlen(p);
str = new char[strlen(p)+1];
strcpy(str, p);
// cout<<"有参构造函数"<<endl;
}
//拷贝构造
my_string(const my_string &other)
{
if(this != &other)
{
this ->len = other.len;
this->str = new char[len+1];
strcpy(this->str, other.str);
}
// cout<<"拷贝构造函数"<<endl;
}
//析构函数
~my_string()
{
delete str;
// cout<<"析构函数"<<endl;
}
//判空函数
bool empty()
{
if(len==0)
return true;
else
return false;
}
//size函数
int size()
{
return len;
}
//at函数
char &at(int pos)
{
return str[pos];
}
//c_str函数
char *c_str()
{
return str;
}
};
int main()
{
my_string s1("hello world");
cout << "s1 = " << s1.c_str() << endl;
my_string s2(s1);
cout << "s2 = " << s2.c_str() << endl;
s2.at(0) = 'H';
s2.at(6) = 'W';
cout << "s2 = " << s2.c_str() << endl;
cout << "s1_size = " << s2.size() << endl;
return 0;
}