C++ | 运算符重载

C111111 / 2023-07-31 / 原文

运算符重载

  • 在类中的函数进行重载(成员函数)

    运算符重载用于重新定义运算符的作用,使用函数名称 operatorOP作为函数名,其中OP为具体的运算符(如operator+

    class Time{
        Time operator+(const Time &t);
    };
    Time a, b;
    Time c = a + b;
    

    在成员函数中重载的运算符,如+ - 等,默认左边的操作数为当前对象,右边的操作数为函数参数。如上面代码中,a+b等价于a.operator+(b)

    而如果使用非成员函数重载+,则需要定义成operator+(const Time &a, const Time &b)

  • 大多数运算符也可以在类之外的函数重载,但下列运算符只能在成员函数中进行重载:

    • = :赋值运算符

    • ():函数调用运算符

    • []:下标运算符

    • ->:通过指针访问类成员的运算符