C++—— 在MyString基础上,重载各类运算符

本文详细介绍了如何在C++中基于MyString类重载各种运算符,包括加法、减法、赋值等,旨在提供全面的运算符重载实现示例。通过代码展示和运行结果,读者可以理解并掌握C++中运算符重载的技巧。
摘要由CSDN通过智能技术生成

在MyString基础上,将能够重载的运算符全部进行重载 

代码如下:

/**
  ******************************************************************************
  * @file              : MyString.cpp
  * @author            : XHJ
  * @date              : 2023/5/11
  * @description       : 在MyString基础上,重载各类运算符
  ******************************************************************************
  */

#include <iostream>
#include <cstring>

using namespace std;

class MyString {
private:
    char *str;          //记录c风格的字符串
    int size;            //记录字符串的实际长度
public:
    //定义无参构造
    MyString() : size(10) {
        str = new char[size];         //构造出一个长度为10的字符串
        strcpy(str, "");
        //cout << "MyString::无参构造,this = " << this << endl;
    }

    //定义有参构造
    MyString(const char *s)          //string  s("hello world")
    {
        size = strlen(s);
        str = new char[size + 1];
        strcpy(str, s);
        //cout << "MyString::有参构造,this = " << this << endl;
    }

    //定义拷贝构造函数
    MyString(const MyString &other) : str(new char[other.size + 1]), size(other.size) {
        strcpy(this->str, other.str);
        //cout << "MyString::拷贝构造,this = " << this << endl;
    }

    //定义拷贝赋值函数
    MyString &operator=(const MyString &other) {
        if (this != &other)      //防止自己给自己赋值
        {
            delete[]this->str;
            this->str = new char[other.size + 1];
            strcpy(this->str, other.str);
            this->size = other.size;
        }
        //cout << "MyString::拷贝赋值,this = " << this << endl;
        return *this;
    }

    //定义析构函数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值