C++&QT-模仿string类

目录

1.mystring.h

2.mystring.cpp

3.mian.cpp

4.运行结果


1.mystring.h

#ifndef MYSTRING_H
#define MYSTRING_H


#include <cstring>

class MyString
{
private:
    char* str; // 保存C风格字符串地址
    int len; // 保存字符串的实际长度
public:
    // 无参构造函数
    MyString() : len(32){ // 给定默认初始大小
        str = new char[len]; // 堆区申请空间
        strcpy(str, ""); // 字符串赋空值
    }
    // 有参构造函数
    MyString(const char* s){
        len = strlen(s); // 计算外部字符串大小,不包含\0
        str = new char[len + 1]; // 堆区申请对应大小空间
        strcpy(str, s); // 拷贝字符串
    }
    // 析构函数
    ~MyString(){
        delete str; // 释放指针成员属性指向的堆空间
    }
    // 拷贝函数
    MyString(MyString &other) : len(other.len){
        str = new char[len + 1]; // 堆区申请对应大小空间
        strcpy(str, other.str); // 拷贝字符串
    }

    // 字符串判空函数
    bool empty();
    // 计算字符串实际长度函数
    int size();
    // 返回C风格字符串
    char* &c_str();
    // at函数
    char &at(int sub);

};


#endif // MYSTRING_H

2.mystring.cpp

#include "mystring.h"


bool MyString::empty(){
    return strlen(this->str) ? false : true;
}

int MyString::size(){
    return strlen(this->str);
}

char* &MyString::c_str(){
    return this->str;
}

char &MyString::at(int sub){
    return this->str[sub];
}

3.mian.cpp

#include <iostream>
#include "mystring.h"

using namespace std;

int main()
{
    // 有参构造函数
    MyString s1("hello");
    cout << "s1 = " << s1.c_str() << endl;

    // 拷贝构造函数
    MyString s2(s1);
    cout << "s2 = " << s2.c_str() << endl;

    // 判空
    if(s2.empty()){
        cout << "s2空" << endl;
    } else {
        cout << "s2非空" << endl;
    }

    // 计算大小
    cout << "s2大小= " << s2.size() << endl;

    // at函数
    s2.at(0) = 'H';
    cout << "s2 = " << s2.c_str() << endl;
    return 0;
}

4.运行结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CG Liu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值