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

实现效果

相关推荐
卷无止境15 小时前
C++ 的Eigen 库全解析
c++
卷无止境15 小时前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴16 小时前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
博客18003 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴3 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨3 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
clint4567 天前
C++进阶(1)——前景提要
c++
夜悊8 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴8 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0018 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp