运算符重载

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;
}
 
相关推荐
Indigo_code1 小时前
【数据结构】【顺序表算法】 删除特定值
数据结构·算法
阿史大杯茶2 小时前
Codeforces Round 976 (Div. 2 ABCDE题)视频讲解
数据结构·c++·算法
LluckyYH2 小时前
代码随想录Day 58|拓扑排序、dijkstra算法精讲,题目:软件构建、参加科学大会
算法·深度优先·动态规划·软件构建·图论·dfs
转调2 小时前
每日一练:地下城游戏
开发语言·c++·算法·leetcode
不穿格子衬衫3 小时前
常用排序算法(下)
c语言·开发语言·数据结构·算法·排序算法·八大排序
wdxylb3 小时前
使用C++的OpenSSL 库实现 AES 加密和解密文件
开发语言·c++·算法
aqua35357423583 小时前
蓝桥杯-财务管理
java·c语言·数据结构·算法
CV金科3 小时前
蓝桥杯—STM32G431RBT6(IIC通信--EEPROM(AT24C02)存储器进行通信)
stm32·单片机·嵌入式硬件·算法·蓝桥杯
sewinger3 小时前
区间合并算法详解
算法
XY.散人3 小时前
初识算法 · 滑动窗口(1)
算法