C++运算符重载实现的过程,代码
#include <iostream>
#include <cstring>
class MyString {
public:
// 无参构造函数
MyString() : str(nullptr), len(0) {}
// 有参构造函数
MyString(const char* s) : str(nullptr), len(0) {
if (s != nullptr) {
len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
}
}
// 拷贝构造函数
MyString(const MyString& other) : str(nullptr), len(other.len) {
if (other.str != nullptr) {
str = new char[len + 1];
strcpy(str, other.str);
}
}
// 析构函数
~MyString() {
if (str != nullptr) {
delete[] str;
}
}
// 拷贝赋值函数
MyString& operator=(const MyString& other) {
if (this != &other) {
if (str != nullptr) {
delete[] str;
}
len = other.len;
if (other.str != nullptr) {
str = new char[len + 1];
strcpy(str, other.str);
} else {
str = nullptr;
}
}
return *this;
}
// 判空函数
bool isEmpty() const {
return len == 0;
}
// size函数
int size() const {
return len;
}
// c_str函数
const char* c_str() const {
return str;
}
// at函数
char& at(int pos) {
if (pos >= 0 && pos < len) {
return str[pos];
} else {
throw std::out_of_range("Index out of range");
}
}
// 加号运算符重载
MyString operator+(const MyString& other) const {
MyString result;
result.len = len + other.len;
result.str = new char[result.len + 1];
strcpy(result.str, str);
strcat(result.str, other.str);
return result;
}
// 加等于运算符重载
MyString& operator+=(const MyString& other) {
MyString temp = *this + other;
*this = temp;
return *this;
}
// 关系运算符重载(>)
bool operator>(const MyString& other) const {
return strcmp(str, other.str) > 0;
}
// 中括号运算符重载
char& operator[](int pos) {
return at(pos);
}
// 友元函数,用于打印MyString对象
friend std::ostream& operator<<(std::ostream& os, const MyString& myString);
private:
char* str;
int len;
};
// 友元函数的实现
std::ostream& operator<<(std::ostream& os, const MyString& myString) {
os << myString.str;
return os;
}
int main() {
MyString s1("Hello");
MyString s2(" World");
MyString s3 = s1 + s2; // 使用+运算符重载
std::cout << "s3: " << s3 << std::endl;
s1 += s2; // 使用+=运算符重载
std::cout << "s1: " << s1 << std::endl;
if (s1 > s3) {
std::cout << "s1 is greater than s3" << std::endl;
} else {
std::cout << "s1 is not greater than s3" << std::endl;
}
return 0;
}