C++学习9.23

1、仿照string类,自己手动实现 My_string

头文件

#ifndef MY_STRING_H
#define MY_STRING_H


#endif // MY_STRING_H

#include <iostream>
#include <cstring>

class My_string
{
private:
    char *ptr;         //指向字符数组的指针
    int size;           //字符串的最大容量
    int len;            //字符串当前容量


public:
    //无参构造
    My_string();


    //有参构造
    My_string(const char* src);
    My_string(int num, char value);
    //拷贝构造
    My_string(const My_string &other);
    //拷贝赋值
    My_string& operator= (const My_string &other);
    //析构函数
    ~My_string();
    //判空
    bool  empty();
    //尾插
    void push_back(char value);
    //尾删
    void pop_back();
    //at函数实现
    char &at(int index);
    //清空函数
    void clear();
    //返回C风格字符串
    char *data();
    //返回实际长度
    int get_length();
    //返回当前最大容量
    int get_size();
};

源函数

#include "My_string.h"

//无参构造
My_string::My_string():size(15)
{
    this->ptr = new char[size];
    this->ptr[0] = '\0';            //表示串为空串
    this->len = 0;
}


//有参构造
My_string:: My_string(const char* src)
{
    len = strlen(src);
    size = len+1;
    ptr = new char[size];
    strcpy(ptr,src);
}
My_string:: My_string(int num, char value): size(num+1),len(num)
{
    ptr = new char[size];
    for(int i=0;i<num;i++)
    {
        ptr[i] = value;
    }
    ptr[num] = '\0';
}
//拷贝构造
My_string:: My_string(const My_string &other):size(other.size),len(other.len)
{
    ptr = new char[size];
    strcpy(ptr,other.ptr);
}
//拷贝赋值
My_string & My_string ::operator =(const My_string &other)
{
    if(this ==&other)
    {
        return *this;
    }
    delete [] ptr;

    size = other.size;
    len = other.len;
    ptr = new char[size];
    strcpy(ptr,other.ptr);

    return *this;
}
//析构函数
My_string:: ~My_string()
{
    delete [] ptr;
}
//判空
bool My_string:: empty()
{
    return len ==0;
}
//尾插
void My_string:: push_back(char value)
{
    if(len+1>=size)
    {
        size *=2;
        char* new_ptr = new char[size];
        strcpy(new_ptr,ptr);
        delete []ptr;
        ptr = new_ptr;
    }

    ptr[len] = value;
    len++;
    ptr[len] = '\0';
}
//尾删
void My_string:: pop_back()
{
    if(len>0)
    {
        len--;
        ptr[len]='\0';
    }
}
//at函数实现
char&My_string:: at(int index)
{

    return ptr[index];
}
//清空函数
void My_string:: clear()
{
    len = 0;
    ptr[0] = '\0';
}
//返回C风格字符串
char*My_string:: data()
{
    return ptr;
}
//返回实际长度
int My_string:: get_length()
{
    return len;
}
//返回当前最大容量
int My_string:: get_size()
{
    return size;
}

2、思维导图正常绘制

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值