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

运行结果:

相关推荐
@areok@9 分钟前
C++mat传入C#OpencvCSharp的mat
开发语言·c++·opencv·c#
小王C语言23 分钟前
【C++进阶】---- map和set的使用
开发语言·c++
Elnaij37 分钟前
从C++开始的编程生活(8)——内部类、匿名对象、对象拷贝时的编译器优化和内存管理
开发语言·c++
liuyao_xianhui1 小时前
内存管理(C/C++)
java·开发语言·c++
饭碗的彼岸one1 小时前
C++设计模式之单例模式
c语言·开发语言·c++·单例模式·设计模式·饿汉模式·懒汉模式
Tim_102 小时前
【算法专题训练】20、LRU 缓存
c++·算法·缓存
Vect__2 小时前
从零实现一个简化版string 类 —— 深入理解std::string的底层设计
c++
hope_wisdom2 小时前
C/C++数据结构之栈基础
c语言·数据结构·c++··stack
ajassi20002 小时前
开源 C++ QT Widget 开发(十四)多媒体--录音机
linux·c++·qt·开源
劲镝丶4 小时前
malloc概述
c语言·开发语言·c++