本文最后更新于320 天前,其中的信息可能已经过时,如有错误请发送邮件到f2213745848@outlook.com
#include <iostream>
#include <cstring>
class MyString {
private:
char* data; // 动态分配的字符数组
public:
// 默认构造函数
MyString() : data(nullptr) {}
// 有参构造函数
MyString(const char* str) {
if (str) {
data = new char[strlen(str) + 1]; // +1 for the null terminator
strcpy(data, str);
} else {
data = nullptr;
}
}
// 拷贝构造函数
MyString(const MyString& other) {
if (other.data) {
data = new char[strlen(other.data) + 1];
strcpy(data, other.data);
} else {
data = nullptr;
}
}
// 赋值运算符重载
MyString& operator=(const MyString& other) {
if (this != &other) {
delete[] data; // 释放原有内存
if (other.data) {
data = new char[strlen(other.data) + 1];
strcpy(data, other.data);
} else {
data = nullptr;
}
}
return *this;
}
// 比较运算符重载
bool operator==(const MyString& other) const {
if (data == nullptr && other.data == nullptr) return true;
if (data == nullptr || other.data == nullptr) return false;
return strcmp(data, other.data) == 0;
}
// 输出运算符重载
friend std::ostream& operator<<(std::ostream& os, const MyString& myStr) {
if (myStr.data) {
os << myStr.data;
}
return os;
}
// 析构函数
~MyString() {
delete[] data; // 释放动态分配的内存
}
};
int main() {
MyString str1("Hello, World!");
MyString str2 = str1; // 拷贝构造
MyString str3;
str3 = str1; // 赋值运算符重载
std::cout << "str1: " << str1 << std::endl;
std::cout << "str2: " << str2 << std::endl;
std::cout << "str3: " << str3 << std::endl;
if (str1 == str2) {
std::cout << "str1 and str2 are equal." << std::endl;
} else {
std::cout << "str1 and str2 are not equal." << std::endl;
}
return 0;
}
代码说明
- 私有成员:
char* data:指向动态分配的字符数组,用于存储字符串。
- 构造函数:
- 默认构造函数:初始化
data为nullptr。 - 有参构造函数:接收一个
const char*类型的字符串,动态分配内存并复制字符串内容。 - 拷贝构造函数:复制另一个
MyString对象的内容,确保深拷贝。
- 赋值运算符重载:支持将一个
MyString对象赋值给另一个,确保释放原有内存并进行深拷贝。 - 比较运算符重载:支持比较两个
MyString对象是否相等。 - 输出运算符重载:支持直接使用
std::cout输出MyString对象。 - 析构函数:释放动态分配的内存,防止内存泄漏。
