运算符重载

运算符重载

运算符重载的本质是函数重载。

语法格式

返值类型 operator 运算符名称(形参列表) 
{
            重载实体; 
}

operator 运算符名称 在一起构成了新的函数名。比如对于自定义类Complex

Complex operator+(const Complex &c1,const Complex &c2);

我们会说,operator+ 重载了运算符+。

两种重载函数

友元函数重载

#include <iostream>
using namespace std;
class Complex
{
public:
    Complex(float x = 0, float y = 0) : _x(x), _y(y) {}
    void dis()
    {
        cout << "(" << _x << "," << _y << ")" << endl;
    }
    friend const Complex operator+(const Complex &c1, const Complex &c2);

private:
    float _x;
    float _y;
};
const Complex operator+(const Complex &c1, const Complex &c2)
{
    return Complex(c1._x + c2._x, c1._y + c2._y);
}
int main()
{
    Complex c1(2, 3);
    Complex c2(3, 4);
    c1.dis();
    c2.dis();
    Complex c3 = operator+(c1, c2);
    c3.dis();
    return 0;
}

成员函数重载

#include <iostream>
using namespace std;
class Complex
{
public:
    Complex(float x = 0, float y = 0) : _x(x), _y(y) {}
    void dis()
    {
        cout << "(" << _x << "," << _y << ")" << endl;
    }
    const Complex operator+(const Complex &another);

private:
    float _x;
    float _y;
};


const Complex Complex::operator+(const Complex &another)
{
    return Complex(this->_x + another._x, this->_y + another._y);
}

int main()
{
    Complex c1(2, 3);
    Complex c2(3, 4);
    c1.dis();
    c2.dis();

    Complex c3 = c1+c2;
    c3.dis();

    return 0;
}

运算符重载小结

不可重载的运算符

.   (成员访问运算符)
.*  (成员指针访问运算符) 
::  (域运算符)
sizeof (长度运算符)
?:  (条件运算符)

只能重载为成员函数的运算符

= 赋值运算符 
[] 下标运算符 
() 函数运算符 
-> 间接成员访问
->* 间接取值访问

常规建议

运算符 建议使用
所有的一元运算符 成员函数重载
+= -= /= *= ^= &= != %= >>= <<= 成员函数重载
其它二员运算符 友元函数重载
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。