c++运算符重载

6.运算符重载

6.1 运算符重载基础

语法:
返回值类型 operator 运算符名称(形参列表){
//TODO;
}

operator是关键字,专门用于定义重载运算符的函数。
我们可以将operator 运算符名称这一部分看做函数名,
对于上面的代码,函数名就是operator+.
不过operator和+中间可以有空格.

#include <iostream>
class Complex{
    public:
        Complex();
        Complex(double real, double imag);

    public:
        Complex operator+(Complex &A) const; //重载运算符 +, 参数是Complex类型数据, 返回值是Complex类型数据.
        bool operator==(Complex &A) const; //重载运算符 ==, 参数是Complex类型数据, 返回值是bool类型数据.
        void show();

    private:
        double m_real;
        double m_imag;
};
Complex::Complex(): m_real(0.0), m_imag(0.0){}
Complex::Complex(double real, double imag): m_real(real), m_imag(imag){}
void Complex::show(){
    std::cout << m_real << "+" << m_imag << "i" << std::endl;
}
Complex Complex::operator+(Complex &A) const {
    //1st
    //Complex B;
    //B.m_real = this->m_real + A.m_real;
    //B.m_imag = this->m_imag + A.m_imag;
    //return B;

    //2nd
    return Complex(this->m_real + A.m_real, this->m_imag + A.m_imag);
}
bool Complex::operator==(Complex &A) const {
    if (this->m_real == A.m_real && this->m_imag == A.m_imag){
        return true;
    } else {
        return false;
    }
}

int main(){
    Complex c0;
    Complex c1(1.1, 1.1);
    Complex c2(1.1, 1.1);
    Complex c3 = c1 + c2; // 编译器转为这个格式 c3 = c1.operator+(c2);

    c0.show();
    c1.show();
    c2.show();
    c3.show();

    if (c1==c2){
        std::cout << "c1==c2" << std::endl;
    } else {
        std::cout << "c1!=c2" << std::endl;
    }
}

//运算符重载时遵循的规则

  1. 不能重载的运算符: 长度运算符sizeof, 条件运算符:?, 成员运算符., 域解析运算符::.
  2. 重载运算符不能改变运算符的优先级.
  3. 重载不会改变运算符的用法, 比如操作数数目, 操作数左右等.
  4. 重载不能有默认参数.
  5. 重载函数可以是类的成员函数, 也可以作为全局函数.
  6. 箭头运算符->, 下标运算符[], 函数调用运算符(), 赋值运算符=, 只能以成员函数的形式重载.

将运算符重载函数作为类的成员函数时,二元运算符的参数只有一个,一元运算符不需要参数。之所以少一个参数,是因为这个参数是隐含的。
将运算符重载函数作为全局函数时,二元操作符就需要两个参数,一元操作符需要一个参数,而且其中必须有一个参数是对象,好让编译器区分这是程序员自定义的运算符,防止程序员修改用于内置类型的运算符的性质。

6.3 重载数学运算符.

四则运算符: +, -, *, /, +=, -=, *=, /= ;
关系运算符: >, <, >=, <=, ==, != ;

6.5 重载输入运算符(>>)输出运算符(<<)

6.6 重载下标运算符([])

6.7 重载自增运算符(++)和自减运算符(--)

6.8 重载new和delete运算符

6.9 重载函数调用运算符(())

posted @ 2022-07-10 15:31  编程驴子  阅读(36)  评论(0编辑  收藏  举报