运算符重载

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;
}
 
相关推荐
董董灿是个攻城狮2 小时前
5分钟搞懂什么是窗口注意力?
算法
Dann Hiroaki2 小时前
笔记分享: 哈尔滨工业大学CS31002编译原理——02. 语法分析
笔记·算法
qqxhb4 小时前
零基础数据结构与算法——第四章:基础算法-排序(上)
java·数据结构·算法·冒泡·插入·选择
FirstFrost --sy5 小时前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
森焱森6 小时前
垂起固定翼无人机介绍
c语言·单片机·算法·架构·无人机
搂鱼1145146 小时前
(倍增)洛谷 P1613 跑路/P4155 国旗计划
算法
Yingye Zhu(HPXXZYY)6 小时前
Codeforces 2021 C Those Who Are With Us
数据结构·c++·算法
无聊的小坏坏7 小时前
三种方法详解最长回文子串问题
c++·算法·回文串
长路 ㅤ   7 小时前
Java后端技术博客汇总文档
分布式·算法·技术分享·编程学习·java后端
秋说8 小时前
【PTA数据结构 | C语言版】两枚硬币
c语言·数据结构·算法