C++作业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)
    {}

    void show()
    {
        cout << "a=" << a << endl;
        cout << "b=" << b << endl;
    }

//    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)const
//    {
//        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;
//    }


};

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(2,3);
    Stu s2(4,5);
    Stu s3 = s1 * s2;
    s3.show();
    cout << "---------------" << endl;
    if(s1 < s2){
        cout << "s1 < s2" << endl;
    }else{
        cout << "s1 > s2" << endl;
    }
    cout << "---------------" << endl;
    s2 -= s1;
    s2.show();
    return 0;
}

运行结果:

相关推荐
神仙别闹3 小时前
基于 C++ 实现两个有序链表序列的交集
java·c++·链表
hansang_IR5 小时前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论
落羽的落羽6 小时前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
刚入门的大一新生6 小时前
Linux-进程控制
linux·运维·服务器·c++
刃神太酷啦6 小时前
Redis 进阶核心:持久化 (RDB/AOF)、事务与主从复制全解析----《Hello Redis!》(5)
linux·c语言·数据库·c++·redis·缓存·bootstrap
喜欢吃燃面9 小时前
深入 C++ STL:从 unordered_set与unordered_map到底层哈希表的原理与实现
数据结构·c++·散列表
FlightYe10 小时前
音视频修炼之基础理论(五):AAC格式与解析
android·linux·c++·音视频·aac
ShineWinsu10 小时前
对于MySQL:数据库的操作的解析
linux·数据库·c++·mysql·面试·笔试·库的操作
云小逸11 小时前
C++ 第一阶段:对象、内存与生命周期
开发语言·c++
夜航海图11 小时前
S-57 数据解剖:把一个 ENC 文件拆给你看
c++