仿照string类,完成myString 类
代码:
#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) //string s("hello world")
{
size = strlen(s);
str = new char[size+1];
strcpy(str, s);
}
//拷贝构造
myString(const myString &other)
{
size=other.size;
str= new char[size];
strcpy(str,other.str);
}
//析构函数
~myString()
{
delete[] str;
}
//拷贝赋值函数
myString & operator=(const myString &other)
{
if(this != &other) //确定不是自己给自己赋值
{
this->size = other.size;
//判断原来指针空间释放被清空
if(this->str != NULL)
{
delete this->str;
}
this->str = new char(*other.str);
}
cout<<"拷贝赋值函数"<<endl;
return *this; //返回自身引用
}
//判空函数
bool string_empty()
{
return size==0;
}
//size函数
unsigned long long int string_size()
{
return strlen(str);
}
//c_str函数
const char* c_str(const myString s1)
{
char *p=new char[s1.size+1];
strcpy(p,s1.str);
return p;
}
//at函数
char &at(int pos)
{
if(pos>=0&&pos<this->size)
{
return str[pos];
}
else
{
cout<<"数据输入错误"<<endl;
return str[0];
}
}
//加号运算符重载
const myString operator+ ( const myString &R)const
{
myString s;
s.size = this->size + R.size;
strcpy(s.str,this->str);
strcat(s.str,R.str);
return s;
}
//加等于运算符重载
myString & operator+=(const myString &R)
{
this->size += R.size;
strcat(this->str,R.str);
return *this; //返回自身的引用
}
//关系运算符重载(>)
bool operator>(const myString &R)const
{
if(strcmp(this->str,R.str)>0)
{
return 1;
}
else
{
return 0;
}
}
//中括号运算符重载
char & operator[](int index)
{
return this->str[index];
}
};
int main()
{
myString s1("hello");
string s2="world";
string s3="war";
myString s4("world");
cout<<s1.string_size()<<endl;
cout<<s1.at(2)<<endl;
s2+=s3;
cout<<s2<<endl;
cout<<s2+s3<<endl;
if(s1 > s4) //调用关系运算符重载函数
{
cout<<"yes"<<endl;
}else
{
cout<<"no"<<endl;
}
return 0;
}
运行结果:
思维导图