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;
}
相关推荐
ai产品老杨1 天前
打破技术壁垒,推动餐饮食安标准化进程的明厨亮灶开源了
前端·javascript·算法·开源·音视频
睡不醒的kun1 天前
leetcode算法刷题的第二十六天
数据结构·c++·算法·leetcode·职场和发展·贪心算法
一匹电信狗1 天前
【Linux我做主】细说进程等待
linux·运维·服务器·c++·ubuntu·小程序·开源
玖釉-1 天前
OpenGL视图变换矩阵详解:从理论推导到实战应用
c++·图形渲染
fangzelin51 天前
基础排序--冒泡--选择--插入
数据结构·c++·算法
THMAIL1 天前
机器学习从入门到精通 - 卷积神经网络(CNN)实战:图像识别模型搭建指南
linux·人工智能·python·算法·机器学习·cnn·逻辑回归
shellvon1 天前
用NCC识别验证码:一个简单但有效的Python实战思路
算法
Hello.Reader1 天前
一文通关 Proto3语法 + 风格的实战指南
java·开发语言·数据库
Jiezcode1 天前
Qt QJsonObject
c++·后端·qt
金古圣人1 天前
hot100 子串
数据结构·c++·算法·leetcode