Overloaded operators grammar explanations

Operator overloading

This essay to explain my knowledge of the C ++ language operator overloading.

First, the use of operator overloading

This is aphilosophyThe question: Why are we overloaded operators?

The reason is that we have the C ++ language has been given operators (including arithmetic operators, and logical operators) but has been operational for a given data type for the C ++ language, if we want our custom data types operation then you need to overload operators, we can understand a prior overloaded operators paired operators redefined.

such as:

double a,b,c;
a=1/3;
b=1/2;
c=a+b;
printf("%lf",c);

Two scores is certainly not the result of adding this program output.
This time we can overload the + operator.

Second, to achieve operator overloading

Syntax is as follows (very important)

<返回类型> operator <运算符符号>(<参数>)
{
    <定义>;
}

Here we give an example.

In the priority queue (The priority_queue), the larger storage element will be placed in the top of the stack. If there is a string or other type int also easy to handle (since they can themselves compare the size of each other), if it is our custom type of structure, it needs to reload <operator.

such as:

struct node
{
    int id;
    double x,y;
}//定义结构体
bool operator <(const node &a,const node &b)
{
    return a.x<b.x && a.y<b.y;
}//重载运算符“<”

Note: The preservation of the structure where an integer variable id, two long floating-point variables x, y, a graph.

Here overloaded operator than the first ratio of the ordinate abscissa.

Third, operator overloading precautions.

The following operators are not overloaded:

Relational operators. ""

Member pointer operator. "*"

Scoping operator "::"

sizeof operator

Ternary operator "?:"

Among allow overloaded operators, can not create a new operator within the operator overloading in C ++ language restrictions already in the range of operators.

Operator overloading substantially overloading.

Well, the basic knowledge of operator overloading basic science has been finished, this is the C ++ programming language is very a very common means of operation. Please be sure to pay attention to and proficiency with plenty of examples.

~ I wish school students AK IOI! !

Guess you like

Origin www.cnblogs.com/fusiwei/p/11314650.html