当前位置: 首页 > article >正文

String的运算符重载

String的运算符重载

主要对String类的=、< 、>、==、+、>>运算符进行重载

示例

class String {

public:
    String(const char* p = nullptr)
    {
        if (p != nullptr)
        {
            _pstr = new char[strlen(p) + 1];
            strcpy(_pstr, p);
        }
        else
        {
            _pstr = new char[1];
            *_pstr = '\0';
        }
    }

    String(const String& rhs)
    {
        _pstr = new char[strlen(rhs._pstr) + 1];
        strcpy(_pstr, rhs._pstr);
    }

    String& operator=(const String& rhs)
    {
        if (this == &rhs)
            return *this;
        delete[]_pstr;
        _pstr = new char[strlen(rhs._pstr) + 1];
        strcpy(_pstr, rhs._pstr);
        return *this;
    }
    
    bool operator<(const String& rhs)
    {
        return strcmp(_pstr, rhs._pstr) < 0;
    }
    bool operator>(const String& rhs)
    {
        return strcmp(_pstr, rhs._pstr) > 0;
    }
    bool operator==(const String& rhs)
    {
        return strcmp(_pstr, rhs._pstr) == 0;
    }

    String operator+(const String& str)
    {
        char* pstr = new char[strlen(_pstr) + strlen(str._pstr) + 1];
        strcpy(pstr, _pstr);
        strcat(pstr, str._pstr);
        String tmp(pstr);
        delete[]pstr;

        return tmp;
    }
    char& operator[](int i)
    {
        return _pstr[i];
    }
    const char& operator[](int i)const
    {
        return _pstr[i];
    }
    friend ostream& operator <<(ostream& out, const String& str);
   
    ~String()
    {
        delete[]_pstr;
        _pstr = nullptr;
    }

private:
    char* _pstr;
};


ostream& operator <<(ostream& out, const String& str)
{
    out << str._pstr;    
    return out;
}

http://www.kler.cn/news/363285.html

相关文章:

  • 实践OpenVINO™ GenAI
  • 机器视觉相机自动对焦算法
  • 家庭宽带的ip地址是固定的吗?宽带ip地址怎么修改‌
  • 监控-08-skywalking监控告警
  • 前端学习---(3)js基础-1
  • 红包雨html
  • C#中跨线程调用的方法一点总结
  • 数据仓库基础概念
  • 新探索研究生英语读写教程pdf答案(基础级)
  • 阿里云服务器如何安装宝塔
  • jupyter DatabaseError: database disk image is malformed 解决办法
  • 分布式检测线路、精准定位故障:输电线路故障定位监测系统
  • 国外电商系统开发-运维系统Docker镜像
  • 构建高效在线教育平台:Spring Boot的力量
  • iPhone图片/照片/视频复制到win10系统的简单方法 - 照片导出
  • Vue 3中的国际化(i18n)实践指南
  • C语言中MySQL库函数
  • MySQL【知识改变命运】09
  • 携程后端JAVA面试汇总
  • SolarWinds Web Help Desk曝出严重漏洞,已遭攻击者利用
  • Golang | Leetcode Golang题解之第496题下一个更大元素I
  • docker清理未使用的 Docker 资源
  • 科技是把双刃剑,巧用技术改变财务预测
  • 什么是SSL证书?
  • 西门子数控软件用在哪些领域及场景
  • 企业数字化转型的关键:构建架构蓝图的最佳实践与实施指南