#include <iostream>
#include <cstring>
using namespace std;
class myString
{
private:
char *str;
int size;
public:
//无参构造
myString():size(20)
{
str=new char [size]; //构造一个长度为10的字符串
strcpy(str,""); //赋值为空串
}
//有参构造
myString(const char *s) //string s("hello")
{
size=strlen(s);
str=new char [size+1];
strcpy(str,s);
}
//拷贝构造
myString(const myString &other):str(new char(*other.str)),size(other.size)
{
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 my_size()
{
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("xxqxxq");
myString s2("gzkgzk");
cout<<s1.c_str()<<endl;
myString s3;
cout<<s3.my_size()<<endl;
s3=s2+s1;
cout<<s3.c_str()<<endl;
//at运算
cout<<s3.at(3)<<endl;
//加等于
s3+=s1;
cout<<s3.c_str()<<endl;
cout<<s3.my_size()<<endl;
//关系运算
if(s3>s1)
{
cout<<"s3>s1"<<endl;
}
else
{
cout<<"s3<s1"<<endl;
}
//中括号
cout<<s2[3]<<" "<<s2[6]<< " "<<s2[4]<<endl;
return 0;
}
C++&QT 作业4
最新推荐文章于 2024-06-12 18:28:23 发布