0

Trying to overload the < and > operators in a c++ class

 template <typename T> bool BinaryTree<T>::operator < (BinaryTree<T> &B) { return (this->count < B.setCount(0)); } template <typename T> float BinaryTree<T>::setCount(float c) { count += c; return count; } 

Where setCount(0) returns the count of the B obj. But this always outputs true no matter the numbers compared.

Changes my code to

template <typename T> bool BinaryTree<T>::operator < (const BinaryTree<T> &B) { return (this->count < B.count); } printf("%c %lf\n", tree[0]->getData(), tree[0]->setCount(0)); printf("%c %lf\n", tree[1]->getData(), tree[1]->setCount(0)); Output > a 0.750000 b 0.250000 if(tree[0] < tree[1]) printf("0 < 1\n"); else printf("1 > 0\n"); Output > 0 < 1 
21
  • 1
    (Should probably be taking a const&.) What does your debugger tell you about the two values you're comparing when you run that code? Commented May 1, 2012 at 8:35
  • 1
    @Mat I doubt setCount is const. Commented May 1, 2012 at 8:37
  • 1
    Are you sure it's B.setCount() you need to compare to? My gut feeling tells me you want to compare to B.count! Oh, and it doesn't matter if count is private. Commented May 1, 2012 at 8:38
  • Try and print the value of ` B.setCount(0)` and this->count and manually check if its a flaw or something true . May be the condition is always true and you have not implemented setCount function correctly Commented May 1, 2012 at 8:38
  • setCount() is correct, printf doesn't work in the operator method Commented May 1, 2012 at 8:39

1 Answer 1

4

This:

 printf("%c %lf\n", tree[0]->getData(), tree[0]->setCount(0)); printf("%c %lf\n", tree[1]->getData(), tree[1]->setCount(0)); 

suggests to me that tree holds pointers to your BinaryTree<T>.

Here, you are comparing pointers, i.e memory addresses, not values:

if(tree[0] < tree[1]) printf("0 < 1\n"); else printf("1 > 0\n"); 

You probably need

if(*(tree[0]) < *(tree[1])) printf("0 < 1\n"); else printf("1 > 0\n"); 
Sign up to request clarification or add additional context in comments.

1 Comment

Very good. I missed that; did have an idea that he might not be calling his defined operator<, but I was not sure why that might happen. This explains it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.