0
struct nodo{ int v,k,dist; nodo(){ } nodo(int _v, int _k, int _dist){ v=_v; k=_k; dist=_dist; } bool operator < (nodo X) const{ return dist>X.dist; } } 

I'm trying to understand this code. but i don't get bool operator part.

what does mean by "return dist>X.dist"? If dist is bigger than X.dist, return true?

2
  • It's a convenience or "syntactic sugar" to be able to write nodeA < nodeB instead of nodeA.dist > nodeB.dist. That's what overloading operators is good for. It's an infix function notation for nodeA.operator<(nodeB) like you'd call any other member function. Commented Mar 26, 2017 at 11:27
  • What terrible book or tutorial are you using that doesn't even try to explain operator overloading? Commented Mar 26, 2017 at 11:39

1 Answer 1

1

what does mean by "return dist>X.dist"? If dist is bigger than X.dist, return true?

You're right.

Operators aren't different from a normal member function. The compiler just execute the function when finds that operator.

You could try put an print statement and see what happens

bool operator < (nodo X) const{ std::cout << "Operator < called" << std::endl; return dist < X.dist; // I changed the sign because it looks more natural } // ... int main() { nodo smallnode(1,2,3); nodo bignode(4,5,6); std::cout << "First node Vs Second Node" << std::endl; if (smallnode < bignode) std::cout << "It's smaller!" << std::endl; else std::cout << "It's bigger!" << std::endl; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.