当前位置:首页 C++ > 正文

C++ string类和常用接口的实现

作者:野牛程序员:2024-01-03 21:04:34 C++阅读 2589

C++的string类提供了一种方便管理字符串的方式,它是标准模板库(STL)中的一部分。下面是string类的一些常用接口和它们的简单实现:

  1. 构造函数:

#include <iostream>
#include <cstring>

class MyString {
private:
    char* str;

public:
    // 默认构造函数
    MyString() : str(nullptr) {}

    // 带参构造函数
    MyString(const char* s) {
        if (s == nullptr) {
            str = nullptr;
        } else {
            str = new char[strlen(s) + 1];
            strcpy(str, s);
        }
    }

    // 拷贝构造函数
    MyString(const MyString& other) {
        if (other.str == nullptr) {
            str = nullptr;
        } else {
            str = new char[strlen(other.str) + 1];
            strcpy(str, other.str);
        }
    }

    // 析构函数
    ~MyString() {
        delete[] str;
    }

    // 其他成员函数(例如赋值运算符、字符串拼接、获取长度等)可根据需要实现
};
  1. 赋值运算符:

MyString& operator=(const MyString& other) {
    if (this != &other) {
        delete[] str;
        if (other.str == nullptr) {
            str = nullptr;
        } else {
            str = new char[strlen(other.str) + 1];
            strcpy(str, other.str);
        }
    }
    return *this;
}
  1. 字符串拼接:

MyString operator+(const MyString& other) const {
    MyString result;
    if (str == nullptr && other.str == nullptr) {
        result.str = nullptr;
    } else if (str == nullptr) {
        result = other;
    } else if (other.str == nullptr) {
        result = *this;
    } else {
        result.str = new char[strlen(str) + strlen(other.str) + 1];
        strcpy(result.str, str);
        strcat(result.str, other.str);
    }
    return result;
}


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击