运算符重载

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;
}
 
相关推荐
雪弯了眉梢6 分钟前
OpenGL(八)摄像机(Camera)
算法·图形渲染·opengl
~~李木子~~6 分钟前
基于 MovieLens-100K 数据集的推荐算法设计与实现
算法·机器学习·推荐算法
Abona7 分钟前
智驾空间智能、物理智能、世界模型相关的最新论文和开源算法链接
算法
sonadorje32 分钟前
群的阶、元素的阶和基点G的阶详解
算法·安全
csuzhucong41 分钟前
一阶鬼魔魔方
算法
夏鹏今天学习了吗1 小时前
【LeetCode热题100(73/100)】买卖股票的最佳时机
算法·leetcode·职场和发展
gaosushexiangji1 小时前
一项基于粒子图像测速(PIV)速度场反演的压力场重构技术
人工智能·算法
Voyager_41 小时前
算法学习记录17——力扣“股票系列题型”
学习·算法·leetcode
雨大王5121 小时前
汽车涂装工艺的智能化与绿色化升级:技术、案例与趋势
算法
XFF不秃头1 小时前
【力扣刷题笔记-在排序数组中查找元素的第一个和最后一个位置】
c++·笔记·算法·leetcode