无效的强制转换为'float'类型

时间:2010-09-24 17:26:02

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

我的班级有问题。我要打造班上的比较操作员 一些代码:

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&);

问题是,我在运算符中有编译错误&lt;功能,在这一行:

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

适当地部分:(浮动)其他

错误消息是:

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

问题的原因是什么?

2 个答案:

答案 0 :(得分:4)

您的转换运算符是非const的,但对象other引用的是const限定的。您必须将const添加到转化运算符,如下所示:

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

const也需要添加到定义中。

答案 1 :(得分:0)

纯粹的猜测。浮点运算符不是常量

相关问题