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;
}
相关推荐
卡提西亚4 分钟前
C++笔记-24-文件读写操作
开发语言·c++·笔记
m0_7482480210 分钟前
C++ 异常处理全解析:从语法到设计哲学
java·c++·word
小白程序员成长日记12 分钟前
2025.11.08 力扣每日一题
算法·leetcode·职场和发展
snakecy15 分钟前
树莓派学习资料共享
大数据·开发语言·学习·系统架构
Nebula_g20 分钟前
C语言应用实例:学生管理系统1(指针、结构体综合应用,动态内存分配)
c语言·开发语言·学习·算法·基础
小叮当⇔20 分钟前
“征服式学习”提示词工具箱
学习·算法
惊讶的猫23 分钟前
字符串- 字符串转换整数 (atoi)
数据结构·算法
开心-开心急了32 分钟前
关于Flutter与Qt for python 的一些技术、开源、商用等问题
开发语言·python·qt·flutter
友友马34 分钟前
『 QT 』按钮类控件属性解析
开发语言·数据库·qt
Evand J36 分钟前
【MATLAB例程】基于噪声协方差自适应的互补滤波器方法vs标准互补滤波,用于融合加速度计和陀螺仪数据,估计角度
开发语言·matlab