8.8C++作业

在类结构体中,运用 成员函数或友元函数 实现算术运算符重载

cpp 复制代码
#include <iostream>

using namespace std;

class Stu
{
    friend const Stu operator/(const Stu &R,const Stu &L);
    friend const Stu operator%(const Stu &R,const Stu &L);
private:
    int a;
    int b;
public:
    Stu()
    {}
    Stu(int i,int k):a(i),b(k)
    {
        cout << "构造函数" << this << endl;
    }
    const Stu operator+(const Stu &r) const
    {
        Stu t;
        t.a=this->a+r.a;
        t.b=b+r.b;
        return t;
    }
    const Stu operator-(const Stu &r) const
    {
        Stu t;
        t.a=a-r.a;
        t.b=b-r.b;
        return t;
    }
    const Stu operator*(const Stu &r) const
    {
        Stu t;
        t.a=this->a*r.a;
        t.b=b*r.b;
        return t;
    }
    void show()
    {
        cout << a << '\t' << b << endl;
    }
};

const Stu operator/(const Stu &R,const Stu &L)
{
    Stu t2;
    t2.a=R.a/L.a;
    t2.b=R.b/L.b;
    return t2;
}
const Stu operator%(const Stu &R,const Stu &L)
{
    Stu t2;
    t2.a=R.a%L.a;
    t2.b=R.b%L.b;
    return t2;
}

int main()
{
    Stu s1(1,2);
    Stu s2(3,4);
    Stu a1,a2,a3,a4;
    a1=s1+s2-s1+s2;
    a2=s1*s2;
    a3=s2/s1;
    a4=s2%s1;
    a1.show();a2.show();a3.show();a4.show();
    cout << "Hello World!" << endl;
    return 0;
}

实现效果

相关推荐
雾岛听风691几秒前
JavaScript基础语法速查手册
开发语言·前端·javascript
c++之路1 分钟前
C++ STL
java·开发语言·c++
geovindu4 分钟前
go:Template Method Pattern
开发语言·后端·设计模式·golang·模板方法模式
瞎折腾啥啊5 分钟前
vcpkg与CMake
linux·c++·cmake·cmakelists
wljy18 分钟前
牛客每日一题(2026.4.30) 整数域二分
c语言·c++·算法·蓝桥杯·二分
卷Java11 分钟前
上下文压缩
开发语言·windows·python
日取其半万世不竭15 分钟前
Minecraft Java版社区服搭建教程(Windows版)
java·开发语言·windows
wjs202416 分钟前
HTML 文本格式化
开发语言
白夜111719 分钟前
C++任务调度与状态机
开发语言·c++·笔记
南宫萧幕23 分钟前
MATLAB/Simulink 从零打通:HEV 能量管理 GA 联合仿真保姆级建模指南
开发语言·算法·matlab·汽车·控制·pid