#include <iostream>
#include <cstring>
using namespace std;
class mystring
{
private:
char* str; //记录c风格字符串
int size; //记录字符串的实际长度
public:
//无参构造
mystring():size(10)
{
str = new char[size];
strcpy(str, "");
cout<<"这是无参构造"<<endl;
}
//有参构造
mystring(const char* s)
{
size = strlen(s);
str = new char[size+1];
strcpy(str, s);
cout<<"这是有参构造"<<endl;
}
//拷贝构造
mystring(const mystring& other):size(other.size)
{
str = new char[size+1];
strcpy(str, other.str);
cout<<"这是拷贝构造"<<endl;
}
//析构函数
~mystring()
{
delete []str;
cout<<"析构函数已经运行"<<endl;
}
//拷贝赋值函数
mystring& operator=(const mystring& other);
//判空函数
bool empty()const;
//size函数
int string_size()const;
//c_str函数
const char* c_str()const;
//at函数
char& at(const int index);
//加号运算符重载
mystring operator+(const mystring& other)const;
//加等于运算符重载
mystring& operator+=(const mystring& string);
//关系运算符重载(>)
bool operator>(const mystring &string) const;
//中括号运算符重载
char& operator[](const int index) const;
};
int main()
{
mystring str1;
mystring str2("hello");
mystring str3;
str3 = str2;
cout<<str3.c_str()<<endl;
cout<<str3.at(2)<<endl;
cout<<str3[2]<<endl;
str1 = str2;
cout<<str1.string_size()<<endl;
str1 += str2;
cout<<str1.c_str()<<endl;
return 0;
}
//拷贝赋值函数
mystring &mystring::operator=(const mystring &other)
{
size = other.size;
delete [] str;
str = new char[size+1];
strcpy(str, other.str);
cout<<"拷贝赋值函数"<<endl;
return *this;
}
//判空函数
bool mystring::empty()const
{
if(strcmp(str, "") == 0)
return true;
else
return false;
}
//size函数
int mystring::string_size() const
{
return size;
}
//c_str函数
const char *mystring::c_str() const
{
return str;
}
//at函数
char& mystring::at(const int index)
{
if(0<=index && index<=size)
return *(str+index);
throw mystring("下标不合法");
}
//加号运算符重载
mystring mystring::operator+(const mystring &other)const
{
mystring new_string = *this;
delete[] new_string.str;
int len = strlen(str)+strlen(other.str)+1;
new_string.str = new char[len];
strcpy(new_string.str,str);
strcat(new_string.str, other.str);
new_string.size = strlen(new_string.str);
// char* c = str;
// strcat(c, other.str);
// mystring new_string(c);
return new_string;
}
//加等于运算符重载
mystring& mystring::operator+=(const mystring &string)
{
int len = strlen(str)+strlen(string.str)+1;
char *s = this->str;
str = nullptr;
str = new char[len];
strcpy(this->str, s);
strcat(this->str, string.str);
size = strlen(str);
delete[] s;
return *this;
}
bool mystring::operator>(const mystring &string) const
{
if(strcmp(this->str,string.str)>0)
return true;
return false;
}
char &mystring::operator[](const int index) const
{
if(index>=0&&index<size)
return *(str+index);
throw mystring("下标不合法");
}
C++实现string类部分内容
于 2023-09-11 21:11:22 首次发布