gpt4 book ai didi

c++ - 具有不同数据类型的 C++ 中的二元运算符重载

转载 作者:搜寻专家 更新时间:2023-10-31 01:37:20 25 4
gpt4 key购买 nike

我正致力于用 C++ 实现 AVL 树。为了保持简洁(和练习),我试图重载树节点的比较运算符。

这是我想要的 find树的功能看:

node* find(int key)
{
node* currentNode = root;

while (currentNode)
{
if (key < *currentNode)
{
currentNode = currentNode.getLeftChild();
}
else if (key > *currentNode)
{
currentNode = currentNode.getRightChild();
}
else
{
return currentNode;
}
}

return nullptr;
}

在这种情况下,我可以重载运算符来比较 intnode像这样:

bool operator<(const int& lhs, const node& rhs)    // friend of node
{
return lhs < rhs.key;
}

但这似乎只适用于 int < node不与 node < int .我需要为 node < int 定义一个单独的函数吗? ?

我还想将此函数模板化,以便我可以将任何东西(本身具有比较运算符)与 node 进行比较小号:

template<typename T> bool operator<(const T& lhs, const node& rhs)    // friend of node
{
return lhs < rhs.key;
}

同样,这适用于 T < node但不适用于 node < T .我需要为 node < T 定义一个函数吗?还有上面的功能?

长话短说

如果我将运算符重载为 bool operator<(const foo& lhs, const bar& rhs) , 我是否还需要定义 bool operator<(const bar& lhs, const foo& rhs)这样操作数就可以左右了吗?像template<typename T> bool operator<(const foo& lhs, const T& rhs)这样的模板函数也是这种情况吗? ?

如果我在这里回答了我自己的问题,我深表歉意,但我能找到的关于运算符重载的唯一资源仅显示了两个参数使用相同类型的示例。我只是想确定我做的是对的,希望下次有人搜索这个问题时这篇文章会出现。

最佳答案

让我们看看你的功能和你使用的命名

bool operator<(const int& lhs, const node& rhs) 

所以 int叫做lhsnoderhs .这些名称与类型位于运算符的哪一侧相匹配。 lhs l离开hside and rhs侧。所以

bool operator<(const int& lhs, const node& rhs) 

只有当你拥有时才会工作

int < node

如果你想拥有

node < int

然后您需要另一个函数,其中 nodelhsintrhs

bool operator<(const node& lhs, const int& rhs) 

现在你可以像这样模板化

template<typename T> bool operator<(const T& lhs, const node& rhs)    // friend of node
{
return lhs < rhs.key;
}

template<typename T> bool operator<(const node& lhs, const T& rhs) // friend of node
{
return lhs.key < rhs;
}

这会给你 operator <对于 T < node::key 的所有类型定义在哪里 Tnode出现在 < 的两侧.

关于c++ - 具有不同数据类型的 C++ 中的二元运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34292219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com