20240902c++mystring

#include <iostream>
#include <cstring>

class Mystring 
{
public:
    // 默认构造函数
    Mystring() : str(nullptr), len(0) {}

    // 有参构造函数
    Mystring(const char* s) 
    {
        len = strlen(s);
        str = new char[len + 1];  // 分配空间,并多留一个位置给'\0'
        strcpy(str, s);
    }

    // 拷贝构造函数
    Mystring(const Mystring& other)
    {
        len = other.len;
        str = new char[len + 1];
        strcpy(str, other.str);
    }

    // 拷贝赋值操作符
    Mystring& operator=(const Mystring& other) 
    {
        if (this == &other) 
        {
            return *this;  // 检查自赋值
        }

        delete[] str;  // 删除旧的字符串数据

        len = other.len;
        str = new char[len + 1];
        strcpy(str, other.str);

        return *this;
    }

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

    // 获取字符串的C风格表示
    const char* c_str() const 
    {
        return str;
    }

    // 获取字符串长度
    int size() const 
    {
        return len;
    }

    // 获取字符串长度
    int length() const
    {
        return len;
    }

    // 判断字符串是否为空
    bool empty() const 
    {
        return len == 0;
    }

    // 获取字符串中某个位置的字符
    char& at(int index) 
    {
        if (index < 0 || index >= len) 
        {
            throw std::out_of_range("Index out of range");
        }
        return str[index];
    }

    // 常量版本的at函数
    const char& at(int index) const 
    {
        if (index < 0 || index >= len) 
        {
            throw std::out_of_range("Index out of range");
        }
        return str[index];
    }

private:
    char* str;  // 指向字符串的指针
    int len;    // 字符串长度
};

int main() {
    Mystring s1("Hello");
    Mystring s2(s1);  // 使用拷贝构造函数
    Mystring s3;
    s3 = s1;  // 使用拷贝赋值操作符

    std::cout << "s1: " << s1.c_str() << ", size: " << s1.size() << std::endl;
    std::cout << "s2: " << s2.c_str() << ", size: " << s2.size() << std::endl;
    std::cout << "s3: " << s3.c_str() << ", size: " << s3.size() << std::endl;

    std::cout << "s1 at 1: " << s1.at(1) << std::endl;
    std::cout << "Is s1 empty? " << (s1.empty() ? "Yes" : "No") << std::endl;

    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值