10.3 C++运算符重载实现的过程,代码

目录

运算符重载背景(operator)

定义

重载的方法

不能重载的运算符

运算符重载注意事项

代码实现

运行结果


运算符重载背景(operator)

自定义的类中,系统默认只提供两个运算符供用户使用,分别是赋值运算符(=)和取地址运算符(&),其余运算符只使用用基本数据类型,对于构造数据类型而言,不可直接使用,除非将该运算符进行重载操作.

定义

运算符重载是静态多态的一种,能够实现"一符多用",使用运算符重载,能够完成运算符作用于类对象之间,使得代码更加简洁、可读性更强。

重载的方法

operator# (#表示运算符号)

不能重载的运算符

1> 成员运算符 .

2> 成员指针运算符 .*

3> 作用域限定符 ::

4> 求字节运算符 sizeof

5> 三目运算符 ?:

运算符重载注意事项

1> 运算符重载,不能改变运算符的优先级

2> 运算符重载,不能改变运算符操作数个数

3> 运算符重载,不能更改运算符的本质逻辑,如不允许在加法运算符重载函数中,实现加法

4> 运算符重载,不能自己造运算符,是在已有的运算符的基础上进行重载操作

5> 运算符重载,不能改变运算符的结合律

6> 运算符重载,一般不设置默认参数

代码实现
cpp 复制代码
#include <iostream>

using namespace std;
//定义一个复数类
class Complex
{
private:
    int real; //实部
    int vir;  //虚部
public:
    Complex(){}
    Complex(int r,int v):real(r),vir(v){}

    //定义展示函数
    void show()
    {
        if(vir>=0)
        {
            cout<<real<<" + "<<vir<<"i"<<endl;
        }else
        {
            cout<<real<<vir<<"i"<<endl;
        }
    }
    //成员函数版实现减法(-)运算符重载
    const Complex operator- (const Complex &R)
    {
        Complex c;
        c.real=this->real-R.real;
        c.vir=this->vir-R.vir;
        return c;
    }
    //重载:+=  实部+=实部 虚部+=虚部
    Complex & operator+=(const Complex &R)
    {
        this->real+=R.real;
        this->vir+=R.vir;
        return *this;
    }
  //重载:-=
    Complex & operator-=(const Complex &R)
    {
        this->real-=R.real;
        this->vir-=R.vir;
        return *this;
    }
     //重载中括号[]运算符
    int & operator[](int index)
    {
        if(index==0)
        {
            return real;
        }
        else if(index==1)
        {
            return vir;
        }
    }


    //重载前置自增运算符重载函数:实部 = 实部+1   虚部=虚部+1
    Complex &operator++()
    {
        ++this->real;
        ++this->vir;

        return *this;
    }
    //重载后置自增运算符重载函数:实部 = 实部+1   虚部=虚部+1
    Complex operator++(int)
    {
        Complex c;

        c.real = this->real++;
        c.vir = this->vir++;

        return c;
    }

};
int main()
{
    Complex c1(5,3);
    Complex c2(2,1);
    c1.show();    //测试

    Complex c3=c1-c2;
    c3.show();

    Complex c4=c1+=c2;   //测试+=
    c4.show();

    Complex c5=c1-=c2;
    c5.show();

    c5[0]=10;        //将实部参数进行修改
    c5.show();

    Complex c6=++c1;   //测试自增
    c6.show();
    Complex c7=c2++;;
    c7.show();
    return 0;
}
运行结果
相关推荐
W.A委员会7 小时前
JS原型链详解
开发语言·javascript·原型模式
止语Lab8 小时前
Go并发编程实战:Channel 还是 Mutex?一个场景驱动的选择框架
开发语言·后端·golang
她说彩礼65万8 小时前
C# 实现简单的日志打印
开发语言·javascript·c#
绿浪19848 小时前
c# 中结构体 的定义字符串字段(性能优化)
开发语言·c#
房开民8 小时前
可变参数模板
java·开发语言·算法
t***5449 小时前
如何在现代C++中更有效地应用这些模式
java·开发语言·c++
itman3019 小时前
C语言、C++与C#深度研究:从底层到现代开发演进全解析
c语言·c++·c·内存管理·编译模型
Victoria.a10 小时前
python基础语法
开发语言·python
xiaoyaohou1111 小时前
023、数据增强改进(二):自适应数据增强与AutoAugment策略
开发语言·python
鬼圣11 小时前
Python 上下文管理器
开发语言·python