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;
}

运行结果:

相关推荐
散峰而望1 小时前
C++数组(二)(算法竞赛)
开发语言·c++·算法·github
利刃大大2 小时前
【动态规划:背包问题】完全平方数
c++·算法·动态规划·背包问题·完全背包
笑非不退2 小时前
C# c++ 实现程序开机自启动
开发语言·c++·c#
AA陈超3 小时前
从0开始学习 **Lyra Starter Game** 项目
c++·笔记·学习·游戏·ue5·lyra
q***T5833 小时前
C++在游戏中的Unreal Engine
c++·游戏·虚幻
保持低旋律节奏3 小时前
C++——C++11特性
开发语言·c++·windows
小张成长计划..5 小时前
【C++】16:模板进阶
c++·算法
CoderIsArt5 小时前
SAM-5 核心类体系的 C++ 完整设计
c++·sam5
CS_浮鱼5 小时前
【Linux进阶】mmap实战:文件映射、进程通信与LRU缓存
linux·运维·c++·缓存
YJlio6 小时前
「C++ 40 周年」:从“野蛮生长的指针地狱”到 AI 时代的系统底座
c++·人工智能·oracle