c++ - 二进制 'operator' : no operator defined which takes a left-hand operand of type 'type' (or there is no acceptable conversion)

标签 c++ compiler-errors operator-overloading

<分区>

我知道为什么会出现此错误,因为我确实实现了Fractionoperator ==。即使我将 f==0 更改为 f==Fraction(1),它也无法编译。

#include <iostream>

using std::cout;

class Fraction
{
public:
    Fraction(int a, int b = 1) {}
    bool operator == (const Fraction&) { return true; }
};

template <typename T>
class Bar
{
public:
    bool test(const T& f) { return (f==0);} // ERROR
};

int main()
{
    Bar<Fraction> f;
    f.test(3);
}

最佳答案

您需要使Fractionoperator== 成员函数成为const 成员函数。否则,它不能与在此表达式中为 const 的 LHS 一起使用:

(f==0)

关于c++ - 二进制 'operator' : no operator defined which takes a left-hand operand of type 'type' (or there is no acceptable conversion),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38810056/

相关文章:

qt - Qt 5.0.1无法启动程序

java - 变量未初始化,我不能将 null 用于 boolean 值

c++ - 通过引用传递 - 运算符重载

c++ - 以十六进制读取文件会给出错误的输出(跳过一些十六进制值)

c++ - 类在单独的文件中 C++

c++ - C++错误: expected primary-expression before ‘}’ token

c++ - 在 C++ 中重载比较运算符,如何与 const 参数进行比较?

c++ - 链接器错误最可爱的二进制文件与 matlab

c++ - 在分配器中使用 new 和 *alloc 函数时有区别吗?

C++ 为赋值重载 operator()