alryosha
alryosha

Reputation: 743

I don't get operator overloading

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?

Upvotes: 0

Views: 42

Answers (1)

amchacon
amchacon

Reputation: 1961

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;
}

Upvotes: 1

Related Questions