实现一个String类 - 自用

实现目标:

String s1="Hello"
String s2="World""
String s3=s1 + s2

cout<<s3
控制台显示hello world

查了好多资料,照着别人的文档实现了一遍。便于理解自己再记录一下:

实现string类是基于字符数组的,因此需要导入必要的包cstring,cstring是C标准库头文件<string.h>的C++标准库版本,包含了C风格字符串(即’\0’结尾字符串)相关的一些类型和函数的声明。需要输出字符串,因此导入必要的包iostream

先把main函数写出来,如下所示:

#include<cstring>
#include<iostream>

int main() {
    string s1 = "hello ";
    string s2 = "world";

    string s3 = s1 + s2;
    std::cout<<s3<<std::endl;
}

现在开始正式实现string类

  1. 在 C++ 中,语句 string s1 = "hello "; 这种形式的初始化被称为拷贝初始化(copy initialization),它会调用 string 类的构造函数来直接构造一个新的 string 对象。该构造函数接受一个 const char* 参数来创建一个新的 string 对象。

    class string {
    
        char* _str;
        size_t _size;
        size_t _capacity;
    
    public:
        
        string():_str(nullptr), _size(0), _capacity(0) {}  // 无参构造函数
        
        string(const char* val) {  // 有参构造函数
            _size = strlen(val);
            _capacity = _size + 1;
            _str = new char[_capacity];
            strcpy(_str, val);
        }
    
        ~string() {
            delete[] _str;
        }
    
    };
    

    到这里,main函数的前两条语句已经可以编译通过了。

  2. string s3 = s1 + s2;,这里涉及到两个字符串的拼接,用的是+,因此需要对+进行运算符重载

        string operator+(const string& other) {
            size_t new_size = _size + other._size;
            size_t new_capacity = new_size + 1;
    
            char* new_str = new char[new_capacity];
            strcpy(new_str, _str);
            strcat(new_str, other._str);
    
            string new_string;
            new_string._str = new_str;
            new_string._size = new_size;
            new_string._capacity = new_capacity;
            return new_string;
        }
    

    到这里,main函数的前三条语句已经可以编译通过了。

  3. std::cout<<s3<<std::endl;,这里要重载左移运算符。

        friend std::ostream& operator<<(std::ostream& stream, const string& source) {
            if(source._str) {
                stream << source._str;
            }
            return stream;
        }
    

    好了,已经可以实现题目的要求了。

参考资料:

如何在C++中创建具有基本功能的自定义String类|极客教程 (geek-docs.com)

【C++】手把手教你写出你自己的String类_自己实现一个string类-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值