Operator Overloading

hi...
I have an struct that operation "<" overloaded in it...
I don't familiar enough with operation overloading...
I have 2 question about it:

1.The "<" operator needs 2 int as input to operate but here we have just one input...

const edge &two

2.what is the const word at the end of the line? what act does it?

here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
struct edge
{
	int p, q, cost;
	edge(int _p = 0, int _q = 0, int _cost = 0)
	{
		p = _p, q = _q, cost = _cost;
	}
	bool operator<(const edge &two)const
	{
		return cost < two.cost;
	}
};
It is funny. You write code and nothing understand what you are writing.:)

Your overloaded operator in fact has two operands. Implicit this (the pointer to the object itself) operand and operand with name two. The const means that the object iteself will not be changed.
The class itself is the first argument. Look at the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
edge e1, e2;
e1.cost = 10;
e2.cost = 4;

if (e1 < e2)   //evaluates to false since e1.cost is greater than (or equal to) e2.cost
{
    //anything here is not executed
}

if (e2 < e1)    //evaluates to true since 4 < 10
{
    //this will be executed
}


The const at the end of the function tells the compiler that calling that function will not change anything inside the class.
thanks alot...
is any digest article about operator overloading in c++ could help me?
Topic archived. No new replies allowed.