Operator Overload

The operator << used earlier is itself in the C language, it is the left shift operator in bit operations. Now it is also used as a stream insertion
operator. This phenomenon of multiple uses of one operator is called operator overloading.
In the C language itself, there is a phenomenon of overloading. For example, & means not only taking the address, but also the AND operation in the bit operation.
* Means both dereference and multiplication operator. It's just this kind of function. The C language doesn't open this kind of function
to developers .
C++ provides an operator overload mechanism. Operators can be overloaded for custom data types. The realization of structured data types can also
have the same operational characteristics as basic data types.
For example, we can easily implement the operation of the basic data type 3 + 5, but indeed cannot implement
the operation of adding two structure type variables.
instance analysis1: C++ classic code

#include <iostream>

using namespace std;

struct Comp
{
    
    
    float real;
    float image;
};

Comp operator+(Comp one, Comp another)
{
    
    
    one.real += another.real;
    one.image += another.image;
    return one;
}

int main()
{
    
    
    Comp c1 = {
    
    1,2};
    Comp c2 = {
    
    3,4};
    Comp sum = c1+c2; //operator+(c1,c2);

    cout<<sum.real<<" "<<sum.image<<endl;

    return 0;
}

Guess you like

Origin blog.csdn.net/Interesting1024/article/details/109211425