简体   繁体   English

C ++类中的运算符重载

[英]Operator overload in c++ class

Trying to overload the < and > operators in a c++ class 尝试重载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;
}

Where setCount(0) returns the count of the B obj. 其中setCount(0)返回B obj的计数。 But this always outputs true no matter the numbers compared. 但是,无论所比较的数字如何,这始终输出true。

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  

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> . 向我建议tree包含指向BinaryTree<T> 指针

Here, you are comparing pointers, ie 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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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