Introduction to operator overloading in C++

The so-called overloading is to give new meaning. Function Overloading allows a function name to have multiple functions and perform different operations under different circumstances. Operator Overloading is also the same. The same operator can have different functions.

In fact, we are already using operator overloading without even realizing it. For example, +the number can perform addition operations on data of different types (int, float, etc.); <<it is both a displacement operator and can output data to the console in conjunction with cout.

C++ itself already has overloading of these operators. C++ also allows programmers to overload operators themselves, which brings us great convenience.

The following code defines a complex number class. Through operator overloading, +the addition operation of complex numbers can be implemented using signs:

    #include <iostream>
    using namespace std;
    class complex{
    public:
        complex();
        complex(double real, double imag);
    public:
        //声明运算符重载
        complex operator+(const complex &A) const;
        void display() const;
    private:
        double

Guess you like

Origin blog.csdn.net/shiwei0813/article/details/132795538