30_操作符重载的概念

0_需要解决的问题

30_操作符重载的概念_第1张图片

编程说明:利用友元关系来解决复数相加问题

#include 

class Complex
{
    int a;
    int b;
public:
    Complex(int a=0, int b=0)
    {
        this->a = a;
        this->b = b;
    }

    int getA()
    {
        return a;
    }
    
    int getB()
    {
        return b;
    }
    
    friend Complex Add(Complex& p1, Complex& p2);
};

Complex Add(Complex& p1, Complex& p2)
{
    Complex ret;
    
    ret.a = p1.a + p2.a;
    ret.b = p1.b + p2.b;
    
    return ret;
}

int main()
{
    Complex c1(1, 2);
    Complex c2(3, 4);
    Complex c3 = Add(c1, c2);
    
    printf("c3.getA() = %d, c3.getB() = %d\n", c3.getA(), c3.getB());

    return 0;
}

输出结果

c3.getA() = 4, c3.getB() = 6

思考:Add函数可以解决Complex对象相加的问题,但是Complex是现实世界中确实存在的复数,并且复数在数学中的地位和普通的实数相同。为什么不能让+操作符也支持复数相加呢

1. 操作符重载

  • C++中的重载能够通过函数的方式扩展操作符的功能,本质上是用特殊形式的函数扩展操作符的功能。
  • 通过operator关键字可以定义特殊的函数operator的本质是通过函数重载操作符,其语法规则如下:
// Sign为系统中预定义的操作符,如 +、-、*、/等
Type operator Sign(const Type p1, const Type p2)
{
    Type ret;

    return ret;
}

编程说明:操作符重载初探

#include 

class Complex
{
    int a;
    int b;
public:
    Complex(int a=0, int b=0)
    {
        this->a = a;
        this->b = b;
    }

    int getA()
    {
        return a;
    }
    
    int getB()
    {
        return b;
    }
    
    friend Complex operator + (const Complex& p1, const Complex& p2);
};

Complex operator + (const Complex& p1, const Complex& p2)
{
    Complex ret;
    
    ret.a = p1.a + p2.a;
    ret.b = p1.b + p2.b;
    
    return ret;
}

int main()
{
    Complex c1(1, 2);
    Complex c2(3, 4);
    Complex c3 = c1 + c2; // ==> operator + (c1, c2);
    
    printf("c3.getA() = %d, c3.getB() = %d\n", c3.getA(), c3.getB());

    return 0;
}

输出结果:

c3.getA() = 4, c3.getB() = 6

问题:通过全局函数实现操作符重载需要使用友元关系,可不可以使用成员函数重载已有的操作符功能,即用类的成员函数扩展操作符的功能?

  • 可以将操作符重载函数定义为类的成员函数
    • 比全局操作符重载函数少一个参数(左操作数),因为在成员函数中可以用this指针来充当左操作数的角色。
    • 不需要依赖友元就可以完成操作符重载
    • 当程序中出现全局操作符重载和成员函数操作符重载,编译器优先在成员函数中寻找操作符重载函数。
class Type
{
public:
    Type Operator Sign(const Type& p)
    {
        Type ret;

        return ret;
    }
}

成员函数重载操作符

#include 

class Complex
{
    int a;
    int b;
public:
    Complex(int a=0, int b=0)
    {
        this->a = a;
        this->b = b;
    }

    int getA()
    {
        return a;
    }
    
    int getB()
    {
        return b;
    }   
    
    Complex operator + (Complex& p)     // 添加成员函数操作符重载函数
    {
        Complex ret;
        
        ret.a = this->a + p.a;
        ret.b = this->b + p.b;      
        
        return ret;
    }
};

int main()
{
    Complex c1(1, 2);
    Complex c2(3, 4);
    Complex c3 = c1 + c2; // ==> c1.operator + (c2)
    
    printf("c3.getA() = %d, c3.getB() = %d\n", c3.getA(), c3.getB());

    return 0;
}

输出结果

c3.getA() = 4, c3.getB() = 6

2. 小结

  • 操作符重载是C++的强大特性之一
  • 操作符重载的本质是通过函数扩展操作符的功能
  • operator关键字是实现操作符重载的关键字
  • 操作符重载遵循相同的函数重载规则
  • 全局函数成员函数都可以实现对操作符的重载

你可能感兴趣的:(30_操作符重载的概念)