#include <iostream>
#include <cstring>
using namespace std;
class my_String
{
private:
int size; //记录字符串的长度
char *str; //记录c风格字符串
public:
//无参构造
my_String():size(10)
{
str = new char[size]; // 构造一个长度为10的字符串
}
//有参构造
my_String(const char *s)
{
size = strlen(s);
str = new char[size+1];
strcpy(str,s);
}
//拷贝构造
my_String(const my_String& other)
{
cout << "拷贝构造" << endl;
size = other.size;
str = new char[size+1];
strcpy(str,other.str);
}
//拷贝赋值
my_String& operator = (const my_String& other)
{
cout << "拷贝赋值" << endl;
if(this == &other)
{
return *this;
}
delete[] str;
size = other.size;
str = new char[size+1];
strcpy(str,other.str);
return *this;
}
//析构函数
~my_String()
{
delete [] str;
}
//判空函数
bool empty() const
{
return (size == 0);
}
//size函数
int length() const
{
return strlen(str);
}
//c_str函数
const char* c_str() const
{
return str;
}
//at函数
char& at(int pos)
{
if(pos >= size || pos < 0)
{
cout << "超出范围" << endl;
}
return str[pos];
}
//[]
const char& operator[](int pos)const
{
return this->str[pos-1];
}
//+=
my_String &operator+=(const my_String &s)
{
my_String temp;
if(this->str!=NULL)
{
temp = new char[strlen(this->str)+1];
strcpy(temp.str,this->str);
delete []this->str;
this->str=NULL;
}
this->str=new char[strlen(temp.str)+strlen(s.str)+1];
strcpy(this->str,temp.str);
strcat(this->str,s.str);
return *this;
}
//+
friend my_String operator+(const my_String &L,const my_String &R);
//strcmp
bool operator==(const my_String &R)const
{
if(strcmp(this->str,R.str) == 0)
{
return true;
}
else {
return false;
}
}
//大于
bool operator>(const my_String &R)const
{
if(strcmp(this->str,R.str) > 0)
{
return true;
}
else {
return false;
}
}
void show()
{
cout << str << endl;
}
friend ostream &operator<<(ostream &L,const my_String &R);
friend istream &operator>>(istream &L,my_String &R);
};
//+
my_String operator+(const my_String &L,const my_String &R)
{
my_String str = L;
str += R;
return str;
}
//cout<<
ostream &operator<<(ostream &L,const my_String &R)
{
L<<R.str;
return L;
}
//cin>>
istream &operator>>(istream &L,my_String &R)
{
if(R.str!=NULL)
{
delete []R.str;
R.str=NULL;
}
char temp[20];
L>>temp;
R.str=new char[strlen(temp)+1];
strcpy(R.str,temp);
return L;
}
int main()
{
my_String s1 = "hello";
my_String s2 = s1;
cout <<"s2为:" ;
s2.show();
my_String s3(s1);
cout << "s3为: " ;
s3.show();
cout<<endl;
cout<<"判空:"<<s1.empty() <<endl;
cout<<"计算长度:"<<s1.length()<<endl;
cout << "s1第4位" << s1.at(4)<<endl;
my_String s4 = "world";
if(s1==s4)
{
cout << "s1=s4"<<endl;
}
else
{
cout << "s1!=s4"<<endl;
}
if(s1>s4)
{
cout<< "s1>s4"<<endl;
}
else
{
cout<<"s1<s4" << endl;
}
cout<<"s4重载<<输出"<<s4<<endl;
my_String s5;
cout << "s5重载>>输入"<<endl;
cin>>s5;
cout<<s5<<endl;
cout<<s5[3]<<endl;
my_String s6;
s3+=s4;
cout<<s3<<endl;
s6 = s3+s4;
cout<<s6<<endl;
cout << "Hello World!" << endl;
return 0;
}
C++ 2023-3-29作业
最新推荐文章于 2024-09-11 23:19:32 发布