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;
}
相关推荐
Morwit7 小时前
【力扣hot100】64. 最小路径和
c++·算法·leetcode
OliverH-yishuihan8 小时前
开发linux项目-在 Windows 上 基于“适用于 Linux 的 Windows 子系统(WSL)”
linux·c++·windows
七禾页丫8 小时前
面试记录12 中级c++开发工程师
c++·面试·职场和发展
zmzb01039 小时前
C++课后习题训练记录Day56
开发语言·c++
编程小Y9 小时前
C++ Insights
开发语言·c++
王老师青少年编程10 小时前
csp信奥赛C++标准模板库STL案例应用5
c++·stl·set·集合·标准模板库·csp·信奥赛
历程里程碑10 小时前
hot 206
java·开发语言·数据结构·c++·python·算法·排序算法
Tipriest_10 小时前
C++ 的 ranges 和 Python 的 bisect 在二分查找中的应用与实现
c++·python·算法·二分法
誰能久伴不乏10 小时前
epoll 学习踩坑:`fcntl` 设置非阻塞到底用 `F_SETFL` 还是 `F_SETFD`?
linux·服务器·网络·c++·tcp/ip
杨忆11 小时前
构建自己的开发工作台MFC
数据库·c++·mfc