views:

55

answers:

2

I'm having problem with my class. I'm going to make comparision operators of my class.
Some code:

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 declaration:

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

The problem is, I've got compile error in operator < function, on this line:

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

Properly in part: (float) other

The error message is:

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

What's the cause of problem?

+3  A: 

Your conversion operator is non-const but the object other refers to is const-qualified. You have to add const to the conversion operators like this:

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

This const also needs to be added to the definitions.

sellibitze
+1 You beat me to my answer. (The other posters should delete theirs like I did mine. Late answers usually get no upvotes.)
Chris Jester-Young
A: 

a pure guess. You float operator is not const

pm100