代码整理, 将学过的三种运算符重载每个至少实现一个运算符的重载

代码:

#include <iostream>

using namespace std;

class Stu
{
    friend const Stu operator*(const Stu &L,const Stu &R);
    friend bool operator<(const Stu &amp;L,const Stu &amp;R);
    friend Stu &amp;operator-=(Stu &amp;L,const Stu &amp;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 &amp;R)const
//    {
//        Stu temp;
//        temp.a = a * R.a;
//        temp.b = b * R.b;
//        return temp;
//    }

//    bool operator<(const Stu &amp;R)const
//    {
//        if(a < R.a &amp;&amp; b < R.b){
//            return true;
//        }else{
//            return false;
//        }
//    }

//    Stu &amp;operator-=(const Stu &amp;R)
//    {
//        a -= R.a;
//        b -= R.b;
//        return *this;
//    }


};

const Stu operator*(const Stu &amp;L,const Stu &amp;R)
{
    Stu temp;
    temp.a = L.a * R.a;
    temp.b = L.b * R.b;
    return temp;
}

bool operator<(const Stu &amp;L,const Stu &amp;R)
{
    if(L.a < R.a &amp;&amp; L.b < R.b){
        return true;
    }else{
        return false;
    }
}

Stu &amp;operator-=(Stu &amp;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 &gt; s2" << endl;
    }
    cout << "---------------" << endl;
    s2 -= s1;
    s2.show();
    return 0;
}

运行结果

原文地址:https://blog.csdn.net/qq_56986199/article/details/134740649

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_27856.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注