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

输出:

相关推荐
让我们一起加油好吗5 小时前
【基础算法】初识搜索:递归型枚举与回溯剪枝
c++·算法·剪枝·回溯·洛谷·搜索
郝学胜-神的一滴5 小时前
Horse3D游戏引擎研发笔记(七):在QtOpenGL环境下,使用改进的Uniform变量管理方式绘制多彩四边形
c++·3d·unity·游戏引擎·图形渲染·虚幻·unreal engine
2401_876221347 小时前
Reachability Query(Union-Find)
c++·算法
躲着人群9 小时前
次短路&&P2865 [USACO06NOV] Roadblocks G题解
c语言·数据结构·c++·算法·dijkstra·次短路
一只鲲10 小时前
56 C++ 现代C++编程艺术5-万能引用
开发语言·c++
小欣加油11 小时前
leetcode 1493 删掉一个元素以后全为1的最长子数组
c++·算法·leetcode
争不过朝夕,又念着往昔12 小时前
即时通讯项目---网关服务
linux·c++·vscode
蓝风破云12 小时前
C++实现常见的排序算法
数据结构·c++·算法·排序算法·visual studio
怀旧,12 小时前
【C++】 9. vector
java·c++·算法
这儿有一堆花15 小时前
C++标准库算法:从零基础到精通
c++