设计字符串类 运算符重载 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;
}

输出:

相关推荐
qq_4298796744 分钟前
省略号和可变参数模板
开发语言·c++·算法
CodeWithMe2 小时前
【C/C++】std::vector成员函数清单
开发语言·c++
uyeonashi2 小时前
【QT控件】输入类控件详解
开发语言·c++·qt
zh_xuan6 小时前
c++ 单例模式
开发语言·c++·单例模式
利刃大大8 小时前
【在线五子棋对战】二、websocket && 服务器搭建
服务器·c++·websocket·网络协议·项目
喜欢吃燃面9 小时前
C++刷题:日期模拟(1)
c++·学习·算法
SHERlocked939 小时前
CPP 从 0 到 1 完成一个支持 future/promise 的 Windows 异步串口通信库
c++·算法·promise
虚拟之10 小时前
36、stringstream
c++
我很好我还能学10 小时前
【面试篇 9】c++生成可执行文件的四个步骤、悬挂指针、define和const区别、c++定义和声明、将引用作为返回值的好处、类的四个缺省函数
开发语言·c++
南岩亦凛汀11 小时前
在Linux下使用wxWidgets进行跨平台GUI开发
c++·跨平台·gui·开源框架·工程实战教程