C++ c+中的运算符过载+;班
尝试在C++类中重载<和>运算符C++ c+中的运算符过载+;班,c++,operator-overloading,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
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;
}
模板
布尔二进制树::运算符<(二进制树和B){
返回(此->计数
其中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
模板
布尔二进制树::运算符<(常量二进制树&B){
返回(此->计数getData(),树[0]->setCount(0));
printf(“%c%lf\n”,树[1]->getData(),树[1]->setCount(0));
输出>
a 75万美元
b 0.250000
if(树[0]<树[1])
printf(“0<1\n”);
else printf(“1>0\n”);
输出>
0 < 1
这是:
printf("%c %lf\n", tree[0]->getData(), tree[0]->setCount(0));
printf("%c %lf\n", tree[1]->getData(), tree[1]->setCount(0));
向我建议,tree
保存指向您的BinaryTree
的指针
这里,您比较的是指针,即内存地址,而不是值:
if(tree[0] < tree[1])
printf("0 < 1\n");
else printf("1 > 0\n");
if(树[0]0\n”);
你可能需要
if(*(tree[0]) < *(tree[1]))
printf("0 < 1\n");
else printf("1 > 0\n");
if(*(树[0])<*(树[1]))
printf(“0<1\n”);
else printf(“1>0\n”);
这是:
printf("%c %lf\n", tree[0]->getData(), tree[0]->setCount(0));
printf("%c %lf\n", tree[1]->getData(), tree[1]->setCount(0));
向我建议,tree
保存指向您的BinaryTree
的指针
这里,您比较的是指针,即内存地址,而不是值:
if(tree[0] < tree[1])
printf("0 < 1\n");
else printf("1 > 0\n");
if(树[0]0\n”);
你可能需要
if(*(tree[0]) < *(tree[1]))
printf("0 < 1\n");
else printf("1 > 0\n");
if(*(树[0])<*(树[1]))
printf(“0<1\n”);
else printf(“1>0\n”);
(可能需要一个常量&
)运行该代码时,调试器会告诉您有关正在比较的两个值的什么信息?@Mat我怀疑setCount是常量。您确定需要比较的是B.setCount()
?我的直觉告诉我你想和B.count比较!哦,count
是否为私有并不重要。请尝试打印'B.setCount(0)`和this->count
的值,并手动检查其是否存在缺陷或是否为真。可能是条件始终为真,并且您尚未实现setCount
函数correctlysetCount(),printf在运算符方法中不起作用(可能需要常量&
)运行该代码时,调试器会告诉您有关正在比较的两个值的什么信息?@Mat我怀疑setCount是常量。您确定需要比较的是B.setCount()
?我的直觉告诉我你想和B.count比较!哦,count
是否为私有并不重要。请尝试打印'B.setCount(0)`和this->count
的值,并手动检查其是否存在缺陷或是否为真。可能是条件始终为真,并且您没有实现setCount
函数correctlysetCount()正确,printf在运算符方法中工作得不太好。我错过了;我有一个想法,他可能不会调用他定义的操作符非常好。我错过了;你有没有想过他可能不会调用他定义的操作符