运算符重载

cpp 复制代码
 
#include <iostream>
#include <cstring>
 
using namespace std;
 
class myString
{
private:
    char *str;
    int size;
public:
    //无参构造
    myString():size(10)
    {
        str = new char[10];
        strcpy(str,"");
    }
    //有参构造
    myString(const char *s)
    {
        size = strlen(s);
        str = new char[size+1];
        strcpy(str,s);
    }
    //拷贝构造
    myString(const myString& other)
    {
        size = other.size;
        str = new char[size + 1];
        strcpy(str, other.str);
    }
    //析构函数
    ~myString()
    {
        delete[] str;
    }
    //拷贝赋值
    myString& operator=(const myString& other)
    {
        if (this != &other)
        {
            delete[] str;
            size = other.size;
            str = new char[size + 1];
            strcpy(str, other.str);
        }
         return *this;
    }
    //加号重载
    myString operator+(const myString& other) const
    {
        myString temp;
        temp.size = this->size + other.size;
        temp.str = new char[temp.size + 1];
        strcpy(temp.str, this->str);
        strcat(temp.str, other.str);
        return temp;
    }
    //加等于重载
    myString& operator+=(const myString& other)
    {
        char* temp = new char[size + other.size + 1];
        strcpy(temp, str);
        strcat(temp, str);
        delete[] str;
        str = temp;
        size += other.size;
        return *this;
    }
    //关系运算符>重载
    bool operator>(const myString& other) const
    {
        return strcmp(str, other.str)>0;
    }
    //c_str函数
    const char* c_str() const
    {
        return str;
    }
    //at函数
    char& at(int pos)
    {
        if (pos >= 0 && pos < size)
        {
            return str[pos];
        }
        else
        {
            cout << "位置不合法" << endl;
            return str[0];
        }
    }
    //中括号运算符重载
    char& operator[](int pos)
    {
        return at(pos);
    }
    //重载函数设置成友元
    friend ostream &operator<<(ostream &out, const myString &c);
};
ostream &operator<<(ostream &out, const myString &c)
{
    cout<<c.c_str()<<"宇宙第一"<<endl;
    return out;
}
 
 
int main()
{
    myString s1("hello");
    cout<<s1.c_str();
    cout<<s1;
    myString s2("world");
    myString s3;
    s3 = s1+" "+s2;
    cout<<s3;
    return 0;
}
 
相关推荐
好吃的肘子1 小时前
Elasticsearch架构原理
开发语言·算法·elasticsearch·架构·jenkins
胡耀超1 小时前
霍夫圆变换全面解析(OpenCV)
人工智能·python·opencv·算法·计算机视觉·数据挖掘·数据安全
软行2 小时前
LeetCode 每日一题 3341. 到达最后一个房间的最少时间 I + II
数据结构·c++·算法·leetcode·职场和发展
nlog3n2 小时前
Go语言交替打印问题及多种实现方法
开发语言·算法·golang
How_doyou_do2 小时前
备战菊厂笔试4
python·算法·leetcode
朱剑君2 小时前
第九天——贪心算法——非递减数组
算法·贪心算法
Wnq100722 小时前
工业场景轮式巡检机器人纯视觉识别导航的优势剖析与前景展望
人工智能·算法·计算机视觉·激光雷达·视觉导航·人形机器人·巡检机器人
天上路人4 小时前
AI神经网络降噪算法在语音通话产品中的应用优势与前景分析
深度学习·神经网络·算法·硬件架构·音视频·实时音视频
好吃的肘子4 小时前
MongoDB 应用实战
大数据·开发语言·数据库·算法·mongodb·全文检索
汉克老师5 小时前
GESP2025年3月认证C++二级( 第三部分编程题(1)等差矩阵)
c++·算法·矩阵·gesp二级·gesp2级