c ++ learning record (seven)

study and practice of overloading c ++

Before a claim is overloaded already declared in the scope of the method has the function declaration or the same name, but the list of parameters and their definitions (realized) are not the same

c ++ class has overloaded operators and overloads

Overloaded function

Statement plurality of similar but different type or number of formal parameters, the compiler by comparing the parameter type parameter type you are using the definition, decided to use the most appropriate definition.
(1) Examples

#include<iostream>
using namespace std;
class Num
{
public:
    void print(int a)
    {
        cout << "返回整数:" << a << endl;
    }
    void print(double a)
    {
        cout << "返回浮点数:" << a << endl;
    }
};
int main()
{
    Num num;
    num.print(1);
    num.print(1.11111);
}

(2) Analysis
Num class function name has two identical but different types of function parameter, call the same functions, different types of input data, the compiler will automatically select the appropriate function output
(3) Results

Operator overloading

Operator is overloaded with special function name, the function name is followed by the key operator and the operator to override symbols. As with other functions, overloaded operators have a return type and an argument list. Most operators can be overloaded, the operator can not be overloaded.

Members of the access operator
. -> member pointer access operator
:: operator domain
sizeof operator length
:? Conditional operator
# preprocessing symbols
(1) Examples

#include<iostream>
using namespace std;
class Num
{
private:
    int a;
    int b;
    int c;

public:
    void set1(int z)
    {
        a = z;
    }
    void set2(int x)
    {
        b = x;
    }
    void set3(int v)
    {
        c = v;
    }
    void sum()
    {
        cout << "三数积得:" << a * b * c << endl;
    }
    Num operator+(const Num& num2)
    {
        Num num1;
        num1.a = this->a + num2.a;
        num1.b = this->b + num2.b;
        num1.c = this->c + num2.c;
        return num1;
    }
};
int main()
{
    Num num3, num4,num5;
    num3.set1(1);
    num3.set2(2);
    num3.set3(3);

    num4.set1(1);
    num4.set2(2);
    num4.set3(3);

    num3.sum();
    num4.sum();
    num5 = num3 + num4;
    num5.sum();
}

(2) Analysis
Set overloaded addition operator, the sum of the two subclasses, after performing operation, returns after a subclass added.
(3) result

Summary: c ++ overloading will become more flexible, there are a lot of follow-up overloaded operators.

Guess you like

Origin www.cnblogs.com/trainking-star/p/12275157.html