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;
}
相关推荐
蜉蝣之翼❉34 分钟前
CRT 不同会导致 fopen 地址不同
c++·mfc
aramae44 分钟前
C++ -- STL -- vector
开发语言·c++·笔记·后端·visual studio
lixzest1 小时前
C++ Lambda 表达式详解
服务器·开发语言·c++·算法
_Chipen2 小时前
C++基础问题
开发语言·c++
灿烂阳光g2 小时前
OpenGL 2. 着色器
c++·opengl
AA陈超3 小时前
虚幻引擎UE5专用服务器游戏开发-20 添加基础能力类与连招能力
c++·游戏·ue5·游戏引擎·虚幻
mit6.8244 小时前
[Meetily后端框架] AI摘要结构化 | `SummaryResponse`模型 | Pydantic库 | vs marshmallow库
c++·人工智能·后端
R-G-B4 小时前
【02】MFC入门到精通——MFC 手动添加创建新的对话框模板
c++·mfc·mfc 手动添加创建新的对话框
linux kernel4 小时前
第七讲:C++中的string类
开发语言·c++
Tipriest_4 小时前
[数据结构与算法] 优先队列 | 最小堆 C++
c++·优先队列·数据结构与算法·最小堆