2024-9-3 C++课后作业

1.题目:实现Mysting类

2.代码如下

#include <iostream>
#include <cstring>
#include <string>

using namespace std;

class Mystring {
public:
    Mystring() { // 无参构造函数
        len = 0;
        str = nullptr;
    }

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

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

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

    // 拷贝赋值函数
    Mystring &operator=(const Mystring &other) {
        if (this != &other) {
            delete[] str; // 释放旧内存
            len = other.len;
            str = new char[len + 1];
            strcpy(str, other.str);
        }
        return *this;
    }

    const char* data() const { // 返回内容的字符数组形式
        return str;
    }

    size_t size() const { // 返回当前字符串拥有的字符数
        return len;
    }

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

    char& at(size_t index) {
        if (index >= len) {
            throw out_of_range("下标数值超出范围");
        }
        return str[index];
    }

private:
    size_t len;  // 使用 size_t 避免负数问题
    char *str;
};

int main(int argc, const char *argv[]) {
    Mystring s1("hello"); // 调用有参构造函数初始化

    cout << s1.at(0) << endl; // 输出第一个字符 'h'

    cout << s1.data() << endl; // 输出整个字符串 "hello"

    cout << s1.empty() << endl; // 字符串不为空,返回 0 

    Mystring s2(""); // 空字符串
    cout << s2.empty() << endl; // 空字符串,返回

	Mystring s3(s1); //调用深拷贝构造函数
	cout<<s3.data()<<endl;

	Mystring s4("hello world");
	s1 = s4; //调用拷贝赋值函数
	cout<<s4.data()<<endl; 

    cout << s1.at(12) << endl; // 尝试访问越界,抛出异常 段错误


    return 0;
}

3.运行结果如下图

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值