项目:实现自定义MyString类
本文最后更新于319 天前,其中的信息可能已经过时,如有错误请发送邮件到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;
}

代码说明

  1. 私有成员
  • char* data:指向动态分配的字符数组,用于存储字符串。
  1. 构造函数
  • 默认构造函数:初始化 datanullptr
  • 有参构造函数:接收一个 const char* 类型的字符串,动态分配内存并复制字符串内容。
  • 拷贝构造函数:复制另一个 MyString 对象的内容,确保深拷贝。
  1. 赋值运算符重载:支持将一个 MyString 对象赋值给另一个,确保释放原有内存并进行深拷贝。
  2. 比较运算符重载:支持比较两个 MyString 对象是否相等。
  3. 输出运算符重载:支持直接使用 std::cout 输出 MyString 对象。
  4. 析构函数:释放动态分配的内存,防止内存泄漏。
文末附加内容
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇