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

实现效果

相关推荐
leonkay43 分钟前
C# 特性(Attribute)——【1】基础讲解
开发语言·青少年编程·面试·c#·.net·个人开发
harmful_sheep1 小时前
java group by常见用法
java·开发语言·python
SKH.1 小时前
Linux软件编程(6)线程间通信
java·开发语言·数据库
whcyhhh1 小时前
头歌实践教学平台:数据科学与大数据技术导论(十六)
大数据·开发语言·python
萌动的小火苗1 小时前
数据结构面试题【无答案】
c语言·开发语言·数据结构·链表
宸津-代码粉碎机1 小时前
AI工程化高阶实战|从Demo到生产落地核心架构、全套源码与避坑指南
java·大数据·开发语言·人工智能·python·架构
XR1234567882 小时前
办公网自主创新建设怎么选?信创办公场景的选型逻辑
开发语言·php
郝学胜-神的一滴3 小时前
Effective Python 条款4:字符串格式化大乱斗
开发语言·网络·python·程序人生·软件工程
Ramble_Naylor3 小时前
只借不占:Rust 的引用与借用
开发语言·rust
FreeTinker3 小时前
Java文件服务器的技术选型与实现路径:从嵌入式工具到企业级系统
java·服务器·开发语言