c++ day 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)
    {}
//    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)
//    {
//        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;
//    }
//----------------------------------------------------------------------------------------------
    void show()
    {
        cout << "a= " << a << " " << "b=" << b << endl;
    }
};
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(10,11);
    Stu s2(10,11);
    Stu s3=s1-s2;
    s3.show();
    if (s3<s1)
    {
        cout << "s3<s1" << endl;
    }
    s1-=s3;
    s1.show();
    return 0;
}
相关推荐
Yupureki23 分钟前
从零开始的C++学习生活 16:C++11新特性全解析
c语言·数据结构·c++·学习·visual studio
紫荆鱼1 小时前
设计模式-迭代器模式(Iterator)
c++·后端·设计模式·迭代器模式
应茶茶1 小时前
C++11 核心新特性:从语法重构到工程化实践
java·开发语言·c++
-森屿安年-2 小时前
STL 容器:stack
开发语言·c++
charlee443 小时前
最小二乘问题详解6:梯度下降法
c++·梯度下降·雅可比矩阵·非线性最小二乘·参数拟合
房开民3 小时前
OpenCV C++ 中,访问图像像素三种常用方法
c++·opencv·计算机视觉
报错小能手3 小时前
C++笔记(面向对象)深赋值 浅赋值
c++·笔记·学习
Maple_land4 小时前
编译器的“隐形约定”与本地变量:解锁Linux变量体系的关键密码
linux·运维·服务器·c++·centos
OC溥哥9994 小时前
C++2D地铁跑酷代码
开发语言·c++
紫荆鱼5 小时前
设计模式-状态模式(State)
c++·后端·设计模式·状态模式