2024.4.26

文章详细描述了C++中如何重载全局运算符如<<,>>,^,~,以及myString类中的+运算符、关系运算和输入输出运算符,以实现自定义对象的序列化和比较操作。
摘要由CSDN通过智能技术生成

friend ostream &operator<<(ostream &out,Sum a);
friend istream &operator>>(istream &in,Sum a);
friend Sum operator^(const Sum c1,const Sum c2);
friend Sum operator~(const Sum c);


//全局<<运算符重载
ostream &operator<<(ostream &out,Sum a)
{
    out << a.rel << "+" << a.vir << endl;
    return out;
}
//全局>>运算符重载
istream &operator>>(istream &in,Sum a)
{
    in >> a.rel >> a.vir;
    return in;
}
//全局^运算符重载
Sum operator^(const Sum c1,const Sum c2)
{
    Sum temp(c1.rel^c2.rel,c1.vir^c2.vir);
    return temp;
}
//全局~运算符重载
Sum operator~(const Sum c)
{
    Sum temp(~c.rel,~c.vir);
    return temp;
}
friend myString operator+(const myString m1,const myString m2);
friend bool operator>(const myString m1,const myString m2);
friend bool operator<(const myString m1,const myString m2);
friend ostream &operator<<(ostream &out,const myString m);
friend istream &operator<<(istream &in,const myString m);


//+运算符重定向
myString operator+(const myString m1,const myString m2)
{
    myString temp(strcat(m1.str,m2.str));
    return temp;
}
//关系运算重载
bool operator>(const myString m1,const myString m2)
{
    int a = strcmp(m1.str,m2.str);
    if(a > 0)
        return 1;
    else
        return 0;
}
bool operator<(const myString m1,const myString m2)
{
    int a = strcmp(m1.str,m2.str);
    if(a < 0)
        return 1;
    else
        return 0;
}
//输入输出运算符重载
ostream &operator<<(ostream &out,const myString m)
{
    out << m.str << endl;
    return out;
}
istream &operator<<(istream &in,const myString m)
{
    in >> m.str ;
    return in;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值