0328 仿照string完成myString类

仿照string完成myString类


class mystring {
private:
    char* data;
    std::size_t size;
public:
    // 构造函数
    //无参
    mystring() : size(10) {
        data = new char[size];
    }
    //有参
    mystring(const char* str) {
        size = strlen(str);
        data = new char[size + 1];
        strncpy(data, str, size + 1);
    }
    //拷贝
    mystring(const mystring& other) {
        size = other.size;
        data = new char[size + 1];
        strncpy(data, other.data, size + 1);
    }

    // 拷贝赋值
    mystring& operator=(const mystring& other) {
        if (this != &other) {
            delete[] data;
            size = other.size;
            data = new char[size + 1];
            strncpy(data, other.data, size + 1);
        }
        return *this;
    }
    // 析构函数
    ~mystring() {
        delete[] data;
    }
    //判空函数
    bool empty() const {
        return size == 0;
    }
    //size
    std::size_t size1() const {
        return size;
    }
    // c_str
    const char* c_str() const {
        return data;
    }


};
好的,下面是一个简单的实现: ```c++ #include <cstring> #include <iostream> class mystring { private: char* str; size_t len; public: mystring() : str(nullptr), len(0) {} mystring(const char* s) : str(nullptr), len(0) { if (s != nullptr) { len = std::strlen(s); str = new char[len + 1]; std::strcpy(str, s); } } mystring(const mystring& other) : str(nullptr), len(other.len) { if (other.str != nullptr) { str = new char[len + 1]; std::strcpy(str, other.str); } } ~mystring() { if (str != nullptr) { delete[] str; } } mystring& operator=(const mystring& other) { if (this != &other) { delete[] str; len = other.len; if (other.str != nullptr) { str = new char[len + 1]; std::strcpy(str, other.str); } else { str = nullptr; } } return *this; } friend std::ostream& operator<<(std::ostream& os, const mystring& s) { return os << s.str; } size_t length() const { return len; } const char* c_str() const { return str; } }; ``` 这是一个简单的 `mystring` ,它具有以下功能: - 默认构造函数和析构函数。 - 从 C 字符串构造函数。 - 拷贝构造函数。 - 赋值运算符。 - `length()` 成员函数,返回字符串长度。 - `c_str()` 成员函数,返回 C 字符串。 示例用法: ```c++ int main() { mystring s1{"Hello world!"}; mystring s2{s1}; mystring s3; s3 = s2; std::cout << s1 << std::endl; std::cout << s2 << std::endl; std::cout << s3 << std::endl; std::cout << "Length of s1: " << s1.length() << std::endl; std::cout << "C string of s2: " << s2.c_str() << std::endl; return 0; } ``` 输出: ``` Hello world! Hello world! Hello world! Length of s1: 12 C string of s2: Hello world! ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值