作业:自己封装string
main.cpp
#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(myString &other):str(new char(*(other.str)))
{
size = other.size;
str = new char[size + 1];
strcpy(str, other.str);
}
//析构函数
~myString()
{
delete str;
};
//判空函数
bool empty()
{
if(strlen(str) == 0)
{
return false;
}
else
{
return true;
}
}
//size函数
int mysize()
{
return size;
}
//c_str函数
char *c_str()
{
return str;
}
//at函数
char &at(int pos)
{
return str[pos];
}
};
int main()
{
//有参类型
char s[50] = "";
cout << "请输入一个字符串:";
gets(s);
myString str(s);
cout << "str = " << str.c_str() << endl;
//拷贝构造函数
myString str1(str);
cout << "str1 = " << str1.c_str() << endl;
//size
cout << "str_size = " << str.mysize() << endl;
//empty
cout << "str_empty = " << str.empty() << endl;
//at函数
int n;
cout << "请输入要查找字符串的第几位:";
cin >> n;
int size = strlen(s);
if(n < 0 || n > size)
{
cout << "访问越界" << endl;
}
cout << "str_at[" << n << "] = " << str.at(n) << endl;
return 0;
}
结果: