C++day1

复制代码
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sstream>
#include <vector>
#include <memory>

using namespace std;

class mystring {
private:
    char* buf;
    int len;
public:
    // 单参构造函数,支持隐式调用,列表初始化 len
    mystring(const char* str)
        : len(strlen(str))
    {
        buf = new char[len + 1];
        strcpy(buf, str);
    }


    // copy 函数,从 mystring 对象拷贝
    void copy(const mystring& other) {
        len = other.len;
        buf = new char[len + 1];
        strcpy(buf, other.buf);
    }

    // copy 函数,从 C 风格字符串拷贝
    void copy(const char* str) {
        len = strlen(str); 
        buf = new char[len + 1];
        strcpy(buf, str);
    }

    // append 函数,追加 mystring 对象内容
    void append(const mystring& other) {
        int newLen = len + other.len;
        char* newBuf = new char[newLen + 1];
        strcpy(newBuf, buf);
        strcat(newBuf, other.buf);
        buf = newBuf;
        len = newLen;
    }

    // append 函数,追加 C 风格字符串内容
    void append(const char* str) {
        int strLen = strlen(str);
        int newLen = len + strLen;
        char* newBuf = new char[newLen + 1];
        strcpy(newBuf, buf);
        strcat(newBuf, str);
        buf = newBuf;
        len = newLen;
    }

    // compare 函数,比较 mystring 对象
    int compare(const mystring& other) {
        return strcmp(buf, other.buf);
    }

    // compare 函数,比较 C 风格字符串
    int compare(const char* str)  {
        return strcmp(buf, str);
    }

    // show 函数,输出字符串
    void show()  {
        cout << buf << endl;
    }

    // at 函数,获取指定位置字符
    char at(int index)  {
        if (index >= 0 && index < len) {
            return buf[index];
        }
        // 这里可根据需求处理越界,简单返回空字符或抛异常等,这里返回空字符示例
        return '\0';
    }
};

int main() {
    mystring str = "hello";
    mystring ptr = "world";

    str.copy(ptr);
    str.copy("你好");

    str.append(ptr);
    str.append("你好");

    str.compare(ptr);
    str.compare("你好");

    str.show();
    cout << str.at(0) << endl;

    return 0;
}
相关推荐
赵英英俊5 分钟前
Python day24
开发语言·python
lifallen8 分钟前
Flink堆状态后端核心:CopyOnWriteStateMap解析
java·大数据·数据结构·数据库·算法·flink·哈希算法
Harbor Lau14 分钟前
多线程插入保证事务的一致性,亲测可用方式一实测
java·开发语言
八月的雨季 最後的冰吻16 分钟前
php算法-- 关联数组使用,优化sip账号去重
开发语言·php
封奚泽优1 小时前
二次元姓名生成器(饮料名+动漫角色名)
开发语言·python
JuneXcy1 小时前
leetcode933最近的请求次数
开发语言·javascript·ecmascript
序属秋秋秋2 小时前
《C++初阶之STL》【vector容器:详解 + 实现】
开发语言·c++·笔记·学习·stl
Brookty2 小时前
【Java学习】匿名内部类的向外访问机制
java·开发语言·后端·学习
科大饭桶5 小时前
数据结构自学Day13 -- 快速排序--“分而治之”
数据结构·算法·排序算法
lixzest6 小时前
快速梳理遗留项目
java·c++·python