运算符重载

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;
}
 
相关推荐
三维重建-光栅投影26 分钟前
VS中将cuda项目编译为DLL并调用
算法
课堂剪切板3 小时前
ch03 部分题目思路
算法
山登绝顶我为峰 3(^v^)34 小时前
如何录制带备注的演示文稿(LaTex Beamer + Pympress)
c++·线性代数·算法·计算机·密码学·音视频·latex
Two_brushes.5 小时前
【算法】宽度优先遍历BFS
算法·leetcode·哈希算法·宽度优先
森焱森7 小时前
水下航行器外形分类详解
c语言·单片机·算法·架构·无人机
QuantumStack9 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
写个博客9 小时前
暑假算法日记第一天
算法
绿皮的猪猪侠9 小时前
算法笔记上机训练实战指南刷题
笔记·算法·pta·上机·浙大
hie9889410 小时前
MATLAB锂离子电池伪二维(P2D)模型实现
人工智能·算法·matlab
杰克尼10 小时前
BM5 合并k个已排序的链表
数据结构·算法·链表