#include <iostream>
#include <cstring>
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);
}
//拷贝构造
myString(const myString &other)
{
size = other.size;
str = new char[size+1];
strcpy(str, other.str);
}
//析构函数
~myString()
{
delete str;
}
//判空函数
void empty()
{
if(strlen(str))
{
cout<<"不为空"<<endl;
return;
}
cout<<"为空"<<endl;
return;
}
//长度
int length()
{
return size;
}
//c_str
void c_string()
{
cout<< str << endl;
}
//at函数
char &at(int pos)
{
return str[pos];
}
};
int main()
{
myString myStr1; //无参函数
myStr1.empty(); //判空
myString myStr2("hello world"); //有参函数
myStr2.empty(); //判空
myStr2.c_string(); //打印字符串
cout << myStr2.at(1) << endl; //at输出
myString myStr3("ni hao,shang hai");
myString myStr4 = myStr3; //拷贝构造
myStr4.c_string();
return 0;
}
2023/5/10 c++实现string类,myString类
最新推荐文章于 2024-05-30 00:29:21 发布