gpt4 book ai didi

c++ - 重载 < 运算符 C++

转载 作者:行者123 更新时间:2023-11-28 03:05:46 27 4
gpt4 key购买 nike

我目前正在尝试为我构建的存储 NFL Plays 的类重载小于运算符。对于我的类(class)项目,我们将数据项插入到 BST 中。我在我的类(class)中以这种方式重载了运算符:

friend bool operator< (const NFLData& lhs, const NFLData& rhs){
if((lhs.getOffenseTeam().compare(rhs.getOffenseTeam())) == 0 ){//They're equal, go left
return true;
}
else{
return false;
}
}

但是,lhs 和 rhs 参数在 Visual Studio 2010 中带有红色下划线,当我尝试运行它时,出现以下错误:

c:\project 4draft\nfldata.h(105): error C2228: left of '.compare' must have class/struct/union
c:\project 4draft\nfldata.h(105): error C2662: 'NFLData::getOffenseTeam' : cannot convert 'this' pointer from 'const NFLData' to 'NFLData &' Conversion loses qualifiers

我从函数的两个参数中删除了 const,它不再强调我的任何代码,但是当我开始编译时,它给了我这些错误:

\bst.h(82): error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const NFLData' (or there is no acceptable conversion)
c:\project 4draft\nfldata.h(104): could be 'bool operator <(NFLData &,NFLData &)' [found using argument-dependent lookup]
while trying to match the argument list '(const NFLData, NFLData)'
c:\project 4draft\bst.h(79) : while compiling class template member function 'void BST<T>::insert(const T &,BST<T>::TreeNode *&) const'
with
[
T=NFLData
]
c:\project 4draft\test.cpp(35) : see reference to class template instantiation 'BST<T>' being compiled
with
[
T=NFLData
]
c:\project 4draft\bst.h(84): error C2679: binary '<' : no operator found which takes a right-hand operand of type 'const NFLData' (or there is no acceptable conversion)
1> c:\project 4draft\nfldata.h(104): could be 'bool operator <(NFLData &,NFLData &)' [found using argument-dependent lookup]
1> while trying to match the argument list '(NFLData, const NFLData)'

我想弄清楚为什么这不起作用,我的 BST 是模板化的。

最佳答案

对于错误 C2662:getOffenseTeam() 需要标记为 const:

rettype_unclear getOffenseTeam() const {
}

因为您不能在常量引用(您的 lhsrhs 是)上调用非常量方法。

对于错误 C2228:确保 getOffenseTeam() 返回的任何内容都有一个 compare 方法。

关于c++ - 重载 < 运算符 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19780376/

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