运算符在c ++类中重载

时间:2012-05-01 08:33:12

标签: c++ operator-overloading

试图重载<和> c ++类中的运算符

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

其中setCount(0)返回B obj的计数。但无论数字比较,这总是输出真实。

将我的代码更改为

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  

1 个答案:

答案 0 :(得分:4)

此:

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

向我建议tree对您的BinaryTree<T>持有指针

在这里,您要比较指针,即内存地址,而不是值:

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

您可能需要

if(*(tree[0]) < *(tree[1]))
   printf("0 < 1\n");
else printf("1 > 0\n");
相关问题