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

运行结果:

相关推荐
万法若空25 分钟前
C/C++基本类型表示范围
c语言·开发语言·c++
凡人叶枫35 分钟前
Effective C++ 条款15:在资源管理类中提供对原始资源的访问
linux·开发语言·c++·stm32·单片机
郝学胜-神的一滴36 分钟前
中级OpenGL教程 009:用环境光告别模型死黑
前端·c++·unity·godot·图形渲染·opengl·unreal
cccyi71 小时前
C++ 面试题整理
c++·面试
代码中介商2 小时前
C++ 智能指针完全指南(二):shared_ptr 深度详解
开发语言·c++
WWW65262 小时前
代码随想录 打卡第五十四天
数据结构·c++·算法
redaijufeng2 小时前
我在C++中深入理解了继承,收获颇丰
java·c++·算法
.千余2 小时前
【C++】C++继承入门(上):继承语法与基本特性详解
开发语言·c++·笔记·学习·其他
哎呦,帅小伙哦3 小时前
一个通用的异步任务提交器
c++
闻道且行之3 小时前
Hair Segmentation:MediaPipe 头发分割模块 CMake 独立编译
c++·人工智能·深度学习·神经网络·opencv·计算机视觉