#include <iostream>
#include <cstring>
using namespace std;
class my_String
{
private:
int size; //记录字符串的长度
char *str; //记录c风格字符串
public:
//无参构造
my_String():size(10)
{
str = new char[size]; // 构造一个长度为10的字符串
}
//有参构造
my_String(const char *s)
{
size = strlen(s);
str = new char[size+1];
strcpy(str,s);
}
//拷贝构造
my_String(const my_String& other)
{
size = other.size;
str = new char[size+1];
strcpy(str,other.str);
}
//拷贝赋值
my_String& operator = (const my_String& other)
{
if(this == &other)
{
return *this;
}
delete[] str;
size = other.size;
str = new char[size+1];
strcpy(str,other.str);
return *this;
}
//析构函数
~my_String()
{
delete [] str;
}
//判空函数
bool empty() const
{
return size == 0?1:0;
}
//size函数
int length() const
{
return strlen(str);
}
//c_str函数
const char* c_str() const
{
return this->str;
}
//at函数
char& at(int pos)
{
if(pos >= size || pos < 0)
{
cout << "超出范围" << endl;
}
else
{
return str[pos];
}
}
void show()
{
cout << str << endl;
}
};
int main()
{
my_String s1 = "hello";
my_String s2 = s1;
cout <<"s2为:" ;
s2.show();
my_String s3(s1);
cout << "s3为: " ;
s3.show();
cout<<endl;
cout<<"判空:"<<s1.empty() <<endl;
cout<<"计算长度:"<<s1.length()<<endl;
cout << "s1第4位" << s1.at(4)<<endl;
return 0;
}
c++仿照string完成mystring类(2023-3-28)
猜你喜欢
转载自blog.csdn.net/k_weihgl/article/details/129827171
今日推荐
周排行