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

运行结果:

相关推荐
努力实干4 小时前
面向对象设计原则——C++
开发语言·c++·数码相机
syagain_zsx7 小时前
jsoncpp 使用指南:编译链接、Json::Value 取值与高频坑
c++·json·库·http格式
布莱克6058 小时前
理解 = delete 与 = default:两种赋值语义的差异
c++
小小、码农9 小时前
[特殊字符]【C++11】类的新功能全面解析:移动构造、移动赋值、default、delete、final 与 override
linux·开发语言·网络·c++
库玛西9 小时前
外部排序全解析:败者树、置换-选择排序与最佳归并树
c语言·数据结构·c++·笔记·考研·算法
General_G11 小时前
创建型模式—原型(Prototype)模式
c++·设计模式·原型模式
syagain_zsx11 小时前
protobuf 实战:从 .proto 到 C++ 序列化的完整链路
c++·学习·程序人生·谷歌·protobuf
welfare96211 小时前
新号别搞:C++_list
开发语言·c++
xiaoye-duck12 小时前
《C++ 项目:手写大模型接入 SDK》云端 API 调用基础与 Apifox 调试实战
网络·c++·语言模型
坤坤子吖12 小时前
Linux 线程同步与互斥——条件变量与线程同步
linux·开发语言·c++·笔记·学习