📜  在C++中可以重载的运算符是什么?(1)

📅  最后修改于: 2023-12-03 15:23:22.658000             🧑  作者: Mango

在C++中可以重载的运算符是什么?

在C++中,可以重载以下运算符:

| 运算符 | 描述 | | --- | --- | | + | 一元正号,二元加法 | | - | 一元负号,二元减法 | | * | 乘法 | | / | 除法 | | % | 取余 | | ^ | 异或 | | & | 按位与 | | | | 按位或 | | ~ | 按位取反 | | ! | 逻辑非 | | && | 逻辑与 | | || | 逻辑或 | | == | 等于 | | != | 不等于 | | < | 小于 | | > | 大于 | | <= | 小于等于 | | >= | 大于等于 | | += | 加等于 | | -= | 减等于 | | *= | 乘等于 | | /= | 除等于 | | %= | 取余等于 | | ^= | 异或等于 | | &= | 按位与等于 | | |= | 按位或等于 | | << | 左移 | | >> | 右移 | | <<= | 左移等于 | | >>= | 右移等于 | | [] | 下标 |

以上运算符可以被类或结构体重载。例如,可以定义一个运算符函数,让两个自定义类型对象可以使用加号运算符相加。重载运算符的函数名为 operator运算符,其中运算符是要重载的符号。例如,重载加号运算符函数的函数名为 operator+()

示例代码:

#include <iostream>
using namespace std;

class Complex {
public:
    Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
    Complex operator+(const Complex &c2) const {
        return Complex(real + c2.real, imag + c2.imag);
    }
    Complex operator-(const Complex &c2) const {
        return Complex(real - c2.real, imag - c2.imag);
    }
    Complex operator*(const Complex &c2) const {
        return Complex(real * c2.real - imag * c2.imag, real * c2.imag + c2.real * imag);
    }
    Complex operator/(const Complex &c2) const {
        double den = c2.real * c2.real + c2.imag * c2.imag;
        return Complex((real * c2.real + imag * c2.imag) / den, (imag * c2.real - real * c2.imag) / den);
    }
    friend ostream& operator<<(ostream &out, const Complex &c){
        out << c.real << "+" << c.imag << "i";
        return out;
    }
    friend istream& operator>>(istream &in, Complex &c){
        in >> c.real >> c.imag;
        return in;
    }
private:
    double real;
    double imag;
};

int main() {
    Complex c1(3, 4), c2(5, -10), c3;
    c3 = c1 + c2;
    cout << c1 << " + " << c2 << " = " << c3 << endl;
    c3 = c1 - c2;
    cout << c1 << " - " << c2 << " = " << c3 << endl;
    c3 = c1 * c2;
    cout << c1 << " * " << c2 << " = " << c3 << endl;
    c3 = c1 / c2;
    cout << c1 << " / " << c2 << " = " << c3 << endl;
    cin >> c1 >> c2;
    cout << c1 << " + " << c2 << " = " << c1 + c2 << endl;
    return 0;
}

输出:

3+4i + 5-10i = 8-6i
3+4i - 5-10i = -2+14i
3+4i * 5-10i = 55-10i
3+4i / 5-10i = -0.48+0.64i
1+2i + 3+4i = 4+6i

注意,不能重载的运算符有:::.*.->?:typeidnewdelete