C++ 实现 String 类

#include <cstring>
#include <iostream>

class String {
public:
    explicit String(const char* cstr = nullptr){//初始化
        if (cstr) {
            pstr = new char[strlen(cstr) + 1];
            len = strlen(cstr);
            strcpy(pstr, cstr);
        } else {
            pstr = new char[1];
            len = 0;
            *pstr = '\0';
        }
    }
    String(const String& str){//拷贝构造
        pstr = new char[str.len + 1];
        len = str.len;
        strcpy(pstr, str.pstr);
    }
    String(String&& str) noexcept { //移动构造(右值
        if (str.pstr != nullptr) {
            pstr = str.pstr;
            str.pstr = nullptr;
            len = str.len;
        }
    }
    String& operator=(const String& str){ //拷贝复制
        if (this == &str) {
            return *this;
        }
        delete[] pstr;
        pstr = new char[str.len + 1];
        len = str.len;
        strcpy(pstr, str.pstr);
        return *this;
    }
    String& operator=(String&& str) noexcept {//移动赋值(右值
        if (this != &str) {
            delete[] pstr;
            pstr = str.pstr;
            str.pstr = nullptr;
            len = str.len;
        }
        return *this;
    }
    ~String(){
        delete []pstr;
        len = 0;
    }
    int size() const{
        return len;
    }
    char* get_c_str() const {
        return pstr;
    }
private:
    char* pstr;
    int len;
};

简单版,其他如 输入输出运算符,[] 等等查看

https://www.cnblogs.com/zhizhan/p/4876093.html

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • memset之类的函数 实现一个String类 引用自:https://www.cnblogs.com/zhizh...
    analanxingde阅读 430评论 0 0
  • CPP 1、在main执行之前和之后执行的代码可能是什么? main函数执行之前,主要就是初始化系统相关资源: 设...
    voidFan阅读 1,737评论 1 6
  • 学习要求 1:C++基础 要求: 1.进一步了解和熟悉VC++6.0开发环境,学会在VC++6.0环境下调试程序;...
    ssy9阅读 206评论 0 1
  • swift社区:http://www.swift51.com[http://www.swift51.com](开源...
    白水灬煮一切阅读 1,980评论 6 6
  • 1. (1) 简述智能指针的原理;(2)c++中常用的智能指针有哪些?(3)实现一个简单的智能指针。 简述智能指针...
    编程半岛阅读 2,968评论 0 17