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;
}
相关推荐
古月-一个C++方向的小白5 小时前
C++11之lambda表达式与包装器
开发语言·c++
tanyongxi667 小时前
C++ AVL树实现详解:平衡二叉搜索树的原理与代码实现
开发语言·c++
斯是 陋室8 小时前
在CentOS7.9服务器上安装.NET 8.0 SDK
运维·服务器·开发语言·c++·c#·云计算·.net
tju新生代魔迷9 小时前
C++:list
开发语言·c++
HHRL-yx9 小时前
C++网络编程 5.TCP套接字(socket)通信进阶-基于多线程的TCP多客户端通信
网络·c++·tcp/ip
tomato0910 小时前
河南萌新联赛2025第(一)场:河南工业大学(补题)
c++·算法
每一天都要努力^12 小时前
C++拷贝构造
开发语言·c++
NoirSeeker14 小时前
在windows平台上基于OpenHarmony sdk编译三方库并暴露给ArkTS使用(详细)
c++·windows·arkts·鸿蒙·交叉编译
落羽的落羽14 小时前
【C++】(万字)一文看懂“类与对象”
c++
闻缺陷则喜何志丹15 小时前
【带权的并集查找】 P9235 [蓝桥杯 2023 省 A] 网络稳定性|省选-
数据结构·c++·蓝桥杯·洛谷·并集查找