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;
}
相关推荐
DechinPhy1 分钟前
使用Python免费合并PDF文件
开发语言·数据库·python·mysql·pdf
qq_252614414 分钟前
python爬虫爬取视频
开发语言·爬虫·python
言之。6 分钟前
Claude Code Skills 实用使用手册
java·开发语言
Swift社区8 分钟前
LeetCode 453 - 最小操作次数使数组元素相等
算法·leetcode·职场和发展
Rinai_R10 分钟前
关于 Go 的内存管理这档事
java·开发语言·golang
咸鱼加辣11 分钟前
【python面试】你x的启动?
开发语言·python
渡我白衣12 分钟前
计算机组成原理(8):各种码的作用详解
c++·人工智能·深度学习·神经网络·其他·机器学习
hoiii18714 分钟前
LR算法辅助的MIMO系统Zero Forcing检测
算法
糖葫芦君16 分钟前
Lora模型微调
人工智能·算法
tyatyatya19 分钟前
MATLAB图形交互教程:鼠标拾取/坐标轴交互/动态绘图实战详解
开发语言·matlab·计算机外设