c++运算符重载

本文介绍了一个使用C++实现的学生类(Stu)示例,该类包含年龄和分数两个属性,并实现了多种运算符重载,如加法、比较等。通过这些重载操作,可以方便地进行学生信息的组合与比较。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>

using namespace std;
class Stu
{
public:
    Stu(){}
    Stu(int a,int s):age(a),score(s){}
    friend Stu operator+(Stu& s1,Stu& s2);
    friend bool operator>(Stu& s1,Stu& s2);
    friend bool operator<(Stu& s1,Stu& s2);
    friend bool operator==(Stu& s1,Stu& s2);
    friend bool operator>=(Stu& s1,Stu& s2);
    friend bool operator<=(Stu& s1,Stu& s2);
    friend bool operator!=(Stu& s1,Stu& s2);
    Stu& operator=(const Stu& s1)
    {
        this->age = s1.age;
        this->score = s1.score;
    }
    void show()
    {
        cout<<age<<" : "<<score<<endl;
    }
private:
    int age,score;
};
Stu operator+(Stu& s1,Stu& s2)
{
    Stu tem;
    tem.age = s1.age+s2.age;
    tem.score=s1.score+s2.score;
    return tem;
}
bool operator>(Stu& s1,Stu& s2)
{
    if(s1.age>s2.age&&s1.score>s2.score)
        return true;
    else
        return false;
}
bool operator<(Stu& s1,Stu& s2)
{
    if(s1.age<s2.age&&s1.score<s2.score)
        return true;
    else
        return false;
}
bool operator==(Stu& s1,Stu& s2)
{
    if(s1.age==s2.age&&s1.score==s2.score)
        return true;
    else
        return false;
}
bool operator>=(Stu& s1,Stu& s2)
{
    if(s1.age>=s2.age&&s1.score>=s2.score)
        return true;
    else
        return false;
}
bool operator<=(Stu& s1,Stu& s2)
{
    if(s1.age<=s2.age&&s1.score<=s2.score)
        return true;
    else
        return false;
}
bool operator!=(Stu& s1,Stu& s2)
{
    if(s1.age!=s2.age&&s1.score!=s2.score)
        return true;
    else
        return false;
}

int main()
{
    Stu s1(1,2);
    s1.show();
    Stu s2(3,4);
    Stu s3;
    s3 = s1+s2;
    s3.show();
    Stu s4;
    s4 = s3;
    s4.show();
    int a = s1>s2;
    int b = s1<s2;
    int c = s4==s3;
    int d = s1>=s2;
    int e = s1<=s2;
    int f = s4!=s3;
    cout<<a<<endl;
    cout<<b<<endl;
    cout<<c<<endl;
    cout<<d<<endl;
    cout<<e<<endl;
    cout<<f<<endl;
    cout << "Hello World!" << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值