c++ - 'this' 参数的类型为 const 但函数未标记为 const C++ 重载运算符

标签 c++

我该如何解决这个问题?

我收到错误:'this' 参数的类型为 const 但函数未标记为 const c++ 重载运算符

template <class T>
class Rational {
private:
    T n = 0;
    T d = 1;
public:
    Rational() = default;
    T numerator() {
        return n;
    }
    T denominator() {
        return d;
    }
};

template <class T>
inline bool const operator ==(const Rational <T> & lhs, const Rational <T>& rhs)  {

    return lhs.numerator() * rhs.denominator() == lhs.denominator() * rhs.numerator();

}

最佳答案

我的猜测是 numerator()denominator() 成员函数不是 const 成员函数。使它们成为 const。之后,上述功能应该可以工作了。

顺便说一句,返回类型不需要是bool const。保持简单并将其更改为 bool

关于c++ - 'this' 参数的类型为 const 但函数未标记为 const C++ 重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58742750/

相关文章:

c++ - 如何将多个 Protocol Buffer 的消息写入一个可追加的压缩文件?

c++ - BOOST_LOG_SEV 在创建线程后破坏 async_read_some

c++ - 条件分支的模板和优化

C++用ifstream打开文件

c++ - int *array = new int[n];这个函数实际上在做什么?

c++ - 在 C/C++ 中使用整数的位标志实际上安全吗?

c# - PInvoke:将文本从 C++ 返回到 C# 时出错

c++ - 为什么在尝试使用我的结构时会出现错误?

c++ - 我需要一些 C++ 结构建议

c++ - 错误 : base class constructor must explicitly initialize parent class constructor