我正在尝试比较类中结构“节点”的两个指针的值。虽然我重载了 < 运算符,但我不确定这样做是否是正确的方法,因为当我运行代码时,我有时会得到正确的答案,有时它会比较错误。是否可以通过这种方式比较值属性? (我必须使用指向 Node 的指针,我不能用其他方式来做)。为什么每次运行程序结果都不一样? 感谢您的帮助!
#include <iostream>
#include "compare.h"
struct Node {
int value;
bool operator >(const Node &n) { return value > n.value ; };
bool operator <(const Node &n) { return value < n.value; };
};
int main()
{
Node *a;
a = new Node;
a->value = 1;
test<Node *> t;
t.compare(a);
delete a;
return 0;
}
这是 compare.h 文件:
template<class TYPE>
class test {
public:
void compare(const TYPE n);
test();
~test();
private:
TYPE n;
};
template<class TYPE>
inline void test<TYPE>::compare(const TYPE a)
{
if (n > a)
std::cout << "n > a";
else if (a>n)
std::cout << "n < a";
}
template<class TYPE>
inline test<TYPE>::test()
{
n = new Node;
n->value = 2;
}
template<class TYPE>
inline test<TYPE>::~test()
{
delete n;
}
最佳答案
在这里,您使用模板参数 Node*
实例化 test
test<Node *> t;
在您的 test::compare
函数中,您正在与模板参数进行比较
template<class TYPE>
inline void test<TYPE>::compare(const TYPE a)
{
if (n > a)
std::cout << "n > a";
else if (a>n)
std::cout << "n < a";
}
如果将 TYPE
替换为您使用的参数 Node*
,您将获得以下内容:
inline void test::compare(const Node* a)
{
if (n > a)
std::cout << "n > a";
else if (a>n)
std::cout << "n < a";
}
因此您可以看到您正在比较 Node*
值。这意味着您正在比较 n
与 a
的内存地址。
您可以通过先解引用指针来解决此问题
template<class TYPE>
inline void test<TYPE>::compare(const TYPE a)
{
if (*n > *a)
std::cout << "n > a";
else if (*a > *n)
std::cout << "n < a";
}
关于c++ - 指向结构的指针的运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44248791/