2010-09-24 48 views
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&); 

问题是,我有编译错误的操作<功能,在这条线:

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

在正确部分:(浮动)其他

呃ror的讯息是:

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

问题的原因是什么?

+0

修复代码时,请考虑使用static_cast (* this)而不是C样式(float)* this'。 – 2010-09-24 17:32:17

回答

4

您的转换运算符是非const的,但对象other指向的是const限定的。你必须添加const的转换操作是这样的:

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

const也需要被添加到定义。

+0

+1你击败了我的答案。 (其他海报应该像我一样删除它们,迟到的答案通常没有upvotes。) – 2010-09-24 17:34:25

0

一个纯粹的猜测。您的浮动操作符不是const

+1

这实在是一个评论,而不是对问题的回答。请使用“添加评论”为作者留下反馈。 – 2012-08-20 07:30:11

+0

@RostyslavDzinko这实际上是正确的答案 - 那它怎么不是一个答案。如果我把“纯粹的猜测”这个词留下来,会不会有问题? – pm100 2012-08-20 16:13:32

相关问题