C++模板类编译错误

C++ template class compilation error

本文关键字:编译 错误 C++      更新时间:2023-10-16

我收到以下编译错误:

main.cc: In function 'int main(int, char**)':¶
main.cc:200: error: no match for 'operator==' in 'rt1 == rt2'¶
triple.hh:124: note: candidates are: bool Triple<T1, T2, T3>::operator==(const    Triple<T1,T2, T3>&) [with T1 = int, T2 = int, T3 = int] <near match>¶
main.cc:27: note:                 bool operator==(const Special&, const Special&)¶

尽管我已经为我的模板类实现了运算符==重载,如下所示:

bool operator==(const Triple<T1, T2, T3>& another) {
    return (a == another.first() and b == another.second() and c == another.third());
}

对于我的模板类:

template <typename T1, typename T2, typename T3>
class Triple

你知道问题可能是什么吗?非常感谢。

您的布尔运算符被声明为非常量。 如果rt1是常量引用,请按如下方式修复它。 请注意添加的const关键字。

bool operator==(const Triple<T1, T2, T3>& another) const {

说明:C++有两种用于重载比较运算符的基本语法:一个成员运算符和一个具有另一个参数,一个静态运算符两个参数。 但是,在这两种情况下,都应确保两个操作数都const,具有各自的语法。

从理论上讲,可以提供不同的const和非const版本的运算符,这些运算符执行微妙的不同操作,因此编译器称您的为近似匹配,但不是匹配。