简体   繁体   中英

How can I overload a 'less than' operator in my C++ class in order to compare consts?

I am trying to overload the less than operator '<' in my class as follows:

//header file

class HuffmanNode{
  private:
    ...
    ...
    int frequency;

  public:
    ...
    ...
    bool operator<(const HuffmanNode &rhs); //overload less than operator
};

//cpp file

bool HuffmanNode::operator<(const HuffmanNode &rhs){
  return frequency < rhs.frequency;
}

I want to be able to compare the nodes as follows:

bool HuffmanTree::compareNode(const HuffmanNode &a, const HuffmanNode &b){
  if (a < b){
    return true;
  }
  else{
    return false;
  }
}

The problem I'm having is finding a way to compare the two nodes as consts. I get an error saying that my operator overloading method needs to be marked as const but changing the code in the header to

const bool operator<(const HuffmanNode &rhs);

and the cpp file code to

const bool HuffmanNode::operator<(const HuffmanNode &rhs){
  return frequency < rhs.frequency;
}

doesn't seem to remove the error.

I have checked out this solution but using the friend keyword didn't seem to work either.

Thanks for any help!

You misunderstand the concept of usage and positioning of the keyword const .

Just to clarify:

const T functionName(something);

means your functionName returns something of the type T and that is a constant.

Now this:

T functionName(something) const;

means your functionName returns something of the type T and that method is not changing anything in the instance and it is safe to use it even with the objects declared as const .

The 2nd option is the one you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM