0

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

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

问题是,我在 operator < 函数中有编译错误,在这一行:

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

部分正确:(浮动)其他

错误信息是:

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

问题的原因是什么?

4

2 回答 2

4

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

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

const也需要添加到定义中。

于 2010-09-24T17:29:50.077 回答
0

一个纯粹的猜测。你浮动运算符不是 const

于 2010-09-24T17:30:45.707 回答