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

实现效果

相关推荐
零匠学堂2025几秒前
移动学习系统,如何提升企业培训效果?
java·开发语言·spring boot·学习·音视频
不会c嘎嘎3 分钟前
【数据结构】AVL树详解:从原理到C++实现
数据结构·c++
小杨快跑~7 分钟前
从装饰者到桥接再到工厂:模式组合的艺术
java·开发语言·设计模式
say_fall9 分钟前
C语言编程实战:每日一题:随机链表的复制
c语言·开发语言·链表
拾贰_C17 分钟前
【Python | Anaconda】 python-Anaconda 一些命令使用
开发语言·python
AKDreamer_HeXY43 分钟前
ABC434E 题解
c++·算法·图论·atcoder
罗湖老棍子43 分钟前
完全背包 vs 多重背包的优化逻辑
c++·算法·动态规划·背包
二川bro44 分钟前
循环性能提升:Python向量化计算技巧
开发语言·python
TracyCoder1231 小时前
大白话讲Java NIO
java·开发语言·nio