代码:
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) //string s("hello world")
{
size = strlen(s)+1;
str = new char[size];
strcpy(str, s);
}
//拷贝构造
myString(char *s,int i):str(new char(*s)),size(i){
strcpy(this->str,s);
this->size = i;
cout<<"拷贝构造函数"<<endl;
}
//析构函数
~myString(){
delete str;
}
//拷贝赋值函数
myString &operator = (const myString &other){
if(&other != this){
this->str = new char[size];
memset(str,0,size);
strcpy(str,other.str);
}
return *this;
}
//判空函数
bool empty(){
if(strlen(str) == 0)
return false;
else
return true;
}
//size函数
int mysize(){
return size;
}
//c_str函数
const char* c_str(){
return str;
}
//at函数
char &at(int pos){
if(pos>=size || pos<0){
cout<<"访问越界"<<endl;
}
return str[pos];
}
//加号运算符重载
const myString operator+(const myString &s)const{
myString m;
strcpy(m.str,this->str);
strcat(m.str,s.str);
m.size = strlen(m.str);
return m;
}
//加等于运算符重载
const myString operator+=(const myString &s){
strcat(this->str,s.str);
this->size = strlen(this->str);
return *this;
}
//关系运算符重载(>)
bool operator >(const myString &s)const{
if(this->size < s.size){
return false;
}
else{
for(int i=0;i<this->size;i++){
if(*(this->str+i)<*(s.str+i)){
return false;
}
}
}
return true;
}
//中括号运算符重载
char & operator[](const int pos)const{
if(pos>=size || pos<0){
cout<<"访问越界"<<endl;
}
return *(str+pos);
}
};
int main(){
//展示字符串
myString s1("ssssyyyy");
myString s2("wwwwhhhh");
cout<<s1.c_str()<<" "<<s2.c_str()<<endl;
//重载加法运算符
myString s3;
cout<<s3.mysize()<<endl;
s3=s1+s2;
cout<<s3.c_str()<<endl;
//at运算
cout<<s3.at(3)<<endl;
//加等于
s3+=s1;
cout<<s3.c_str()<<endl;
cout<<s3.mysize()<<endl;
//关系运算
if(s3>s1){
cout<<"s3>s1"<<endl;
}
else
cout<<"s3<s1"<<endl;
//中括号
cout<<s2[3]<<" "<<s2[6]<< " "<<s2[8]<<endl;
return 0;
}