作业0829

仿照string类,实现myString

#ifndef MYSTRING_H
#define MYSTRING_H
#include <iostream>

using namespace std;

class myString
{
    private:
        char *str;//记录c风格的字符串
        int size = 0; //记录字符串的实际长度
        int capacity = 0;//字符串的最大容量
    public:
        //无参构造
        myString();
        //有参构造
        myString(const char *s);//有参构造     string  s("hello wirld");
        //判空函数
        bool empty();
        //返回当前对象分配的存储空间能保存的字符数量
        int get_capacity();
        //size函数
        int get_size();
        //c_str函数
        char *c_str();
        //at函数
        char &at(int index);
        //push_back
        bool push_back(const char ch);
        //二倍扩容
        void expend();
};

#endif // MYSTRING_H
#include "myString.h"

//无参构造
myString::myString():size(10), capacity(10)
{
    str = new char[size];
}
//有参构造
myString::myString(const char *s)//有参构造     string  s("hello world");
{
    for(int i=0; size = i, s[i] != 0; i++);
    str = new char[size+1];
    memcpy(str, s, size);
    str[size] = '\0';
    capacity = size;
}

//判空函数
bool myString::empty()
{
    return size == 0;
}

//返回当前对象分配的存储空间能保存的字符数量
int myString::get_capacity()
{
    return capacity;
}

//size函数
int myString::get_size()
{
    return size;
}

//c_str函数
char *myString::c_str()
{
    return str;
}

//at函数
char& myString::at(int index)
{
    return str[index];
}

//push_back
bool myString::push_back(const char ch)
{
    if(capacity == size)
    {
        expend();
    }

    at(size) = ch;
    size++;

    return true;
}

//二倍扩容
void myString::expend()
{
    capacity *= 2;
    char *temp = new char[capacity];
    memcpy(temp, str, size);
    delete []str;
    str = temp;
}
#include "myString.h"

int main()
{
    myString str("hello");
    cout << str.at(2) << endl;
    cout << "字符串实际长度为:" << str.get_size() << endl;
    cout << "字符串容量为:" << str.get_capacity() << endl;
    str.at(0) = 'H';
    cout << "str = " << str.c_str() << endl;
    str.push_back('A');
    cout << "str = " << str.c_str() << endl;
    cout << "字符串实际长度为:" << str.get_size() << endl;
    cout << "字符串容量为:" << str.get_capacity() << endl;

    return 0;
}

思维导图:

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值