C++ day3

题目:仿照string类,实现myString

cpp 复制代码
#include <iostream>
#include <cstring> 
using namespace std;
//仿照string完成myString类
class myString
{
    private:
        char *str;          //记录c风格的字符串
        int size;            //记录分配的内存大小
        int len;          //字符串长度
    public:
        //无参构造
        myString():size(10),len(0)
        {
            str = new char[size]; //构造出一个长度为10的字符串
            str[0]='\0';
        }
        //有参构造
        myString(const char *s): len(strlen(s)), size(len + 1)        //有参构造     string  s("hello wirld");
        {
            str = new char[size];
            strcpy(str,s);
        }
        //析构函数
        ~myString()
        {
            delete [] str;
        }
        //判空函数
        bool empty()
        {
            return len==0;
        }
        //size函数
        int get_size()
        {
            return size;
        }
        //或许字符串长度
        int get_len()
        {
            return len;
        }
        //c_str函数
        const char* c_str()
        {
            return str;
        }

        //at函数
        char &at(int index)
        {
            if (index < 0 || index >=len)
            {
                 throw std::out_of_range("查找范围错误");
            }
           return str[index];
        }
        //二倍扩容
        void resize(int newSize)
        {
               if (newSize > size)
               {
                   char *newStr = new char[newSize];
                   std::strcpy(newStr, str);
                   delete[] str;
                   str = newStr;
                   size = newSize;
               }
        }
};

int main()
{
    myString s("Hello, World!");
        std::cout << s.c_str() << std::endl;
        std::cout << "len: " << s.get_len() << std::endl;
        std::cout << "Size: " << s.get_size() << std::endl;

        std::cout << "第七个字符为: " << s.at(7) << std::endl;

    return 0;
}
相关推荐
极小狐2 分钟前
如何构建容器镜像并将其推送到极狐GitLab容器镜像库?
开发语言·数据库·机器学习·gitlab·ruby
MarkHard1233 分钟前
Leetcode (力扣)做题记录 hot100(34,215,912,121)
算法·leetcode·职场和发展
多多*35 分钟前
Java反射 八股版
java·开发语言·hive·python·sql·log4j·mybatis
正在走向自律35 分钟前
从0到1:Python机器学习实战全攻略(8/10)
开发语言·python·机器学习
爱喝茶的小茶44 分钟前
构造+简单树状
数据结构·算法
悦悦子a啊1 小时前
PTA:jmu-ds-最短路径
c++·算法·图论
FY_20181 小时前
键盘输出希腊字符方法
开发语言
西西弗Sisyphus1 小时前
Python 处理图像并生成 JSONL 元数据文件 - 灵活text版本
开发语言·python
Kidddddult1 小时前
力扣刷题Day 46:搜索二维矩阵 II(240)
算法·leetcode·力扣
小王努力学编程2 小时前
高并发内存池(三):TLS无锁访问以及Central Cache结构设计
jvm·数据结构·c++·学习