在MyString基础上,将能够重载的运算符全部进行重载
代码如下:
/**
******************************************************************************
* @file : MyString.cpp
* @author : XHJ
* @date : 2023/5/11
* @description : 在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, "");
//cout << "MyString::无参构造,this = " << this << endl;
}
//定义有参构造
MyString(const char *s) //string s("hello world")
{
size = strlen(s);
str = new char[size + 1];
strcpy(str, s);
//cout << "MyString::有参构造,this = " << this << endl;
}
//定义拷贝构造函数
MyString(const MyString &other) : str(new char[other.size + 1]), size(other.size) {
strcpy(this->str, other.str);
//cout << "MyString::拷贝构造,this = " << this << endl;
}
//定义拷贝赋值函数
MyString &operator=(const MyString &other) {
if (this != &other) //防止自己给自己赋值
{
delete[]this->str;
this->str = new char[other.size + 1];
strcpy(this->str, other.str);
this->size = other.size;
}
//cout << "MyString::拷贝赋值,this = " << this << endl;
return *this;
}
//定义析构函数