【C++】30操作符重载的概念 operator关键字

【C++】30操作符重载的概念 operator关键字_第1张图片

#include 

class Complex 
{
    int a;
    int b;
public:
    Complex(int a = 0, int b = 0)
    {
        Complex::a = a;
        Complex::b = b;
        //this->a = a;
        //this->b = b;
    }
    
    int getA()
    {
        return a;
    }
    
    int getB()
    {
        return b;
    }
    
    friend Complex Add(const Complex& p1, const Complex& p2);
};

Complex Add(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 = Add(c1, c2); // c1 + c2
    
    printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB());
    
    return 0;
}
c3.a = 4, c3.b = 6

操作符重载

C++中的重载能够扩展操作符的功能

操作符的重载以函数的方式进行

本质:

用特殊形式的函数扩展操作符的功能

通过operator关键字可以定义特殊的函数

operator的本质是通过函数重载操作符

#include 

class Complex 
{
    int a;
    int b;
public:
    Complex(int a = 0, int b = 0)
    {
        Complex::a = a;
        Complex::b = b;
        //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; // c1 + c2
    
    printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB());
    
    return 0;
}

输出:

c3.a = 4, c3.b = 6

可以将操作符重载函数定义为类的成员函数

比全局操作符重载函数少一个参数(左操作数)

不需要依赖友元就可以完成操作符重载

编译器优先再成员函数中寻找操作符的重载函数

#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 + (const Complex& p)
    {
        Complex ret;
        printf("Complex operator + (const Complex& p)\n");
        ret.a = this->a + p.a;
        ret.b = this->b + p.b;
        
        return ret;
    }
    
    friend Complex operator + (const Complex& p1, const Complex& p2);
};

Complex operator + (const Complex& p1, const Complex& p2)
{
    Complex ret;
    printf("Complex operator + (const Complex& p1, const Complex& p2)\n");
    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; // c1.operator + (c2)
    
    printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB());
    
    return 0;
}

输出:

c3.a = 4, c3.b = 6

小结:

操作符重载是C++强大的特性之一

操作符重载的本质是通过函数扩展操作符的功能

operator关键字是实现操作符重载的关键

操作符重载遵循相同的函数重载规则

全局函数和成员函数都可以实现对操作符的重载

你可能感兴趣的:(c++)