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

实现效果

相关推荐
宋康几秒前
C/C++ 指针避坑20条
c语言·开发语言·c++
爱丫爱19 分钟前
Python中常见库 PyTorch和Pydantic 讲解
开发语言·pytorch·python
Ryan_Gosling20 分钟前
C++-构造函数-接口
开发语言·c++
ceffans29 分钟前
PDF文档中文本解析
c++·windows·pdf
SummerGao.36 分钟前
Windows 快速搭建C++开发环境,安装C++、CMake、QT、Visual Studio、Setup Factory
c++·windows·qt·cmake·visual studio·setup factory
仟濹40 分钟前
【二分搜索 C/C++】洛谷 P1873 EKO / 砍树
c语言·c++·算法
服务端相声演员1 小时前
Oracle JDK、Open JDK zulu下载地址
java·开发语言
YH_DevJourney1 小时前
Linux-C/C++《C/8、系统信息与系统资源》
linux·c语言·c++
19岁开始学习1 小时前
Go学习-入门
开发语言·学习·golang
青铜念诗2 小时前
python脚本文件设置进程优先级(在.py文件中实现)
开发语言·python