gpt4 book ai didi

c++ - 如何正确重载函数

转载 作者:行者123 更新时间:2023-11-28 01:40:47 25 4
gpt4 key购买 nike

您好,我只是想知道如何在二叉搜索树中正确地重载函数。这是我的代码:

int LessThan(E itm1, E itm2) {
if (itm1 < itm2) {return -1;}
else if (itm1 > itm2) {return 1;}
else if (itm1 == itm2) {return 0;}
}

int LessThan(string s1, string s2) { // Incase it is a string, we need to define <= and >= differently
return this->compare(s1, s2);
}

不幸的是,我收到以下错误:

binarySearchTree.h:33:9: error: ‘int binarySearchTree<E>::LessThan(std::__cxx11::string, std::__cxx11::string) [with E = std::__cxx11::basic_string<char>; std::__cxx11::string = std::__cxx11::basic_string<char>]’ cannot be overloaded
int LessThan(string s1, string s2) { // Incase it is a string, we need to define <= and >= differently
^
binarySearchTree.h:27:9: error: with ‘int binarySearchTree<E>::LessThan(E, E) [with E = std::__cxx11::basic_string<char>]’
int LessThan(E itm1, E itm2) {
^

最佳答案

重载不是您问题的答案。当您的模板使用 std::string 实例化时,您正在尝试具有特定行为。正确的技术是显式特化。在您的模板定义下添加以下内容,如下所示:

template<>
int binarySearchTree<std::string>::LessThan(std::string s1, std::string s2) {
return this->compare(s1, s2);
}

关于c++ - 如何正确重载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47258163/

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