设计字符串类 运算符重载 C++实现 QT环境

**问题:**设计字符串类, 支持下面的操作

MyString s1;// 默认构造函数

MyString s2("hello");// 含参构造函数

MyString s3(s1); // 传参构造函数

MyString s4(5, 'c');// 自定义构造函数

=// 运算符重载

== != > < // 运算符重载


代码:

cpp 复制代码
#include <iostream>
#include <cstring>

using namespace std;

class Mystring{
    // <<
    friend ostream& operator<<(ostream &out,Mystring &s);
    // >>
    friend istream& operator>>(istream &in,Mystring &s);
private:
    char *m_space; // 存储数据
    size_t m_len; // 字符串长度
public:
    // 默认构造函数
    Mystring(){
        m_space = new char;
        strcpy(m_space,"");
        m_len = 0;
    }
    // 构造函数
    Mystring(const char *indata){
        m_len = strlen(indata);
        m_space = new char[m_len + 1];
        strcpy(m_space,indata);
    }
    // 拷贝构造函数(深拷贝)
    Mystring(const Mystring &s){
        m_len = s.m_len;
        m_space = new char[m_len + 1];
        strcpy(m_space,s.m_space);
    }
    // 析构函数
    ~Mystring(){
        if(m_space != nullptr){
            delete [] m_space;
            m_space = nullptr;
        }
    }
    // 重载赋值运算符 =
    Mystring& operator=(const Mystring &s){
        if(m_space != nullptr){
            delete [] m_space;
            m_space = nullptr;
        }
        m_len = s.m_len;
        m_space = new char[m_len + 1];
        strcpy(m_space,s.m_space);
        return *this;
    }
};
// <<
ostream& operator<<(ostream &out,Mystring &s){
    out<<s.m_space;
    return  out;
}
istream& operator>>(istream &in,Mystring &s){
    // 对之前的内存进行管理(避免内存泄漏)
    if(s.m_space != nullptr){
        delete [] s.m_space;
        s.m_space = nullptr;
    }
    // 输入新的字符串
    char buf[1024];
    in>>buf;
    s.m_len = strlen(buf);
    s.m_space = new char[s.m_len + 1];
    strcpy(s.m_space,buf);
    return  in;
}
int main(){
    Mystring s1;
    Mystring s2("Hello");
    cout<<"Please input data:"<<endl;
    cin>>s2;
    s1 = s2;
    cout<<"s2: "<<s2<<endl;
    cout<<"s1: "<<s1<<endl;
    return 0;
}

输出:

相关推荐
dtq04246 小时前
C++小案例 - 日志实战
开发语言·c++
码匠许师傅6 小时前
【C++三方组件】Qt 概览:桌面 C++ 的事实标准与许可证三轨
开发语言·c++·qt
码匠许师傅7 小时前
【C++三方组件】POCO:跨平台系统编程全家桶
开发语言·c++
小王C语言8 小时前
Qt常用控件:输入类控件,单行/多行输入框、下拉框、(日期)微调框、旋钮、滑动条
开发语言·qt
1001101_QIA8 小时前
.exe does not seem to be a Qt executable.
开发语言·qt
WBluuue10 小时前
数据结构与算法:分块(一):块状数组、块状链表
数据结构·c++·算法·链表
必须得开心呀11 小时前
字节序大小端科普
c++·程序人生
会编程的小孩12 小时前
C++ 子集
c++
SunkingYang12 小时前
C++20 vs C++17:新特性对比与用法指南
c++·c++20·特性·版本·新特性·对比·c++17
前进吧-程序员12 小时前
C++20 协程入门实战:从 co_await 到一个 100 行的异步任务调度器
网络·c++·c++20