【问题标题】:invalid cast to type 'float'无效强制转换为“float”类型
【发布时间】:2010-09-24 17:26:01
【问题描述】:

我的课有问题。我要为我的班级制作比较运算符。
一些代码:

CVariable::operator float ()
{
    float rt = 0;
    std::istringstream Ss (m_value);
    Ss >> rt;
    return rt;
};

bool CVariable::operator < (const CVariable& other)
{
    if (m_type == STRING || other.Type() == STRING)
        int i = 0; // placeholder for error handling
    else
        return (float) *this < (float) other;
};

类声明:

class CVariable
{
    public:
    inline VARTYPE Type () const {return m_type;};
    inline const std::string& Value () const {return m_value;};
    bool SetType (VARTYPE);

    private:
     int m_flags;
    VARTYPE m_type;
    std::string m_value;

    public:

    // ...


    operator int ();
    operator float ();
    operator std::string ();

    //...


    inline bool operator == (const CVariable& other) {return m_value == other.Value();};
    inline bool operator != (const CVariable& other) {return m_value != other.Value();};
    bool operator < (const CVariable&);

问题是,我在操作符

return (float) *this < (float) other;

部分正确:(浮动)其他

错误信息是:

cvariable.cpp|142|error: invalid cast from type 'const MCXJS::CVariable' to type 'float'|

问题的原因是什么?

【问题讨论】:

  • 在修复代码时,请考虑使用 static_cast&lt;float&gt;(*this) 而不是 C 风格的 (float) *this

标签: c++ conversion-operator comparison-operators


【解决方案1】:

您的转换运算符是非常量的,但 other 引用的对象是 const 限定的。您必须像这样将const 添加到转换运算符中:

operator int () const;
operator float () const;
operator std::string () const;

这个const 也需要添加到定义中。

【讨论】:

  • +1 你打败了我的回答。 (其他发帖者应该像我一样删除他们的。迟到的答案通常不会得到支持。)
【解决方案2】:

纯属猜测。你的浮动运算符不是 const

【讨论】:

  • 这真的是评论,而不是问题的答案。请使用“添加评论”为作者留下反馈。
  • @RostyslavDzinko 这实际上是正确的答案 - 那么它怎么不是答案。如果我把“纯粹的猜测”这个词去掉可以吗
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多