c++ day 4

代码整理, 将学过的三种运算符重载,每个至少实现一个运算符的重载:分别是-,-=,<。

cpp 复制代码
#include <iostream>

using namespace std;
class Stu
{
    friend const Stu operator-(const Stu &L,const Stu &R);
    friend bool operator<(const Stu &L,const Stu &R);
    friend Stu &operator-=(Stu &L,const Stu &R);
private:
    int a;
    int b;
public:
    Stu(){}
    Stu(int a,int b):a(a),b(b)
    {}
//    const Stu operator-(const Stu &R)const //算数成员函数-=
//    {
//        Stu temp;
//        temp.a=a-R.a;
//        temp.b=b-R.b;
//        return temp;
//    }

 //--------------------------------------------------------------------------------------------------
//    bool operator<(const Stu &R)
//    {
//        if (a<R.a && b<R.b)
//        {
//            return true;
//        }
//        else
//        {
//            return false;
//        }
//    }
//-----------------------------------------------------------------------------------------------
//    Stu &operator-=(const Stu &R)
//    {
//        a-=R.a;
//        b-=R.b;
//        return *this;
//    }
//----------------------------------------------------------------------------------------------
    void show()
    {
        cout << "a= " << a << " " << "b=" << b << endl;
    }
};
const Stu operator-(const Stu &L,const Stu &R)
{
    Stu temp;
    temp.a=L.a-R.a;
    temp.b=L.b-R.b;
    return  temp;
}
bool operator<(const Stu &L,const Stu &R)
{
    if (L.a<R.a && L.b<R.b)
    {
        return  true;
    }
    else
    {
        return false;
    }
}
Stu &operator-=(Stu &L,const Stu &R)
{
    L.a-=R.a;
    L.b-=R.b;
    return L;
}
int main()
{
    Stu s1(10,11);
    Stu s2(10,11);
    Stu s3=s1-s2;
    s3.show();
    if (s3<s1)
    {
        cout << "s3<s1" << endl;
    }
    s1-=s3;
    s1.show();
    return 0;
}
相关推荐
2401_841495647 分钟前
【数据结构】英文单词词频统计与检索系统
数据结构·c++·算法·排序·词频统计·查找·单词检索
Elnaij18 分钟前
从C++开始的编程生活(17)——多态
开发语言·c++
Frank_refuel21 分钟前
C++之多态详解
开发语言·c++
Elnaij25 分钟前
从C++开始的编程生活(18)——二叉搜索树基础
开发语言·c++
王老师青少年编程31 分钟前
2024年6月GESP真题及题解(C++七级): 黑白翻转
c++·题解·真题·gesp·csp·七级·黑白翻转
ouliten33 分钟前
C++笔记:std::span
c++·笔记
小尧嵌入式33 分钟前
【Linux开发二】数字反转|除数累加|差分数组|vector插入和访问|小数四舍五入及向上取整|矩阵逆置|基础文件IO|深入文件IO
linux·服务器·开发语言·c++·线性代数·算法·矩阵
一只小bit36 分钟前
Qt 网络:包含Udp、Tcp、Http三种协议的客户端实践手册
前端·c++·qt·页面
jojo_zjx36 分钟前
GESP 23年6月2级 找素数
c++
kimicsdn38 分钟前
opentelemetry-demo currency cpp 项目编译流程分享
c++·cmake·libprotobuf-dev