c++string类的模拟实现:运算符重载
作者:野牛程序员:2024-01-03 14:28:28 C++阅读 2900
字符串类的模拟实现可以包括一系列常见的操作,例如构造函数、析构函数、赋值运算符重载、拷贝构造函数、加法运算符重载等。以下是一个简化版本的C++字符串类的模拟实现,包含了运算符重载:
#include <iostream>
#include <cstring>
class MyString {
private:
char* str;
public:
// 构造函数
MyString(const char* s = nullptr) {
if (s == nullptr) {
str = new char[1];
str[0] = '\\0';
} else {
str = new char[std::strlen(s) + 1];
std::strcpy(str, s);
}
}
// 析构函数
~MyString() {
delete[] str;
}
// 拷贝构造函数
MyString(const MyString& other) {
str = new char[std::strlen(other.str) + 1];
std::strcpy(str, other.str);
}
// 赋值运算符重载
MyString& operator=(const MyString& other) {
if (this != &other) {
delete[] str;
str = new char[std::strlen(other.str) + 1];
std::strcpy(str, other.str);
}
return *this;
}
// 加法运算符重载
MyString operator+(const MyString& other) const {
MyString result;
result.str = new char[std::strlen(str) + std::strlen(other.str) + 1];
std::strcpy(result.str, str);
std::strcat(result.str, other.str);
return result;
}
// 输出运算符重载
friend std::ostream& operator<<(std::ostream& os, const MyString& s) {
os << s.str;
return os;
}
};
int main() {
MyString s1("Hello");
MyString s2("World");
MyString s3 = s1 + s2;
std::cout << s3 << std::endl;
return 0;
}在这个例子中,模拟实现了字符串类MyString,包括了构造函数、析构函数、拷贝构造函数、赋值运算符重载、加法运算符重载以及输出运算符重载。这个简单的实现可以用来执行基本的字符串操作。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

