Search code examples
c++operator-overloadingtypecast-operator

Overloaded typecasts don't work


I've built a little class representing a decimal number, called Complex. I want to be able to cast it to double, so here's my code

Complex.h

public:
    operator double();

Complext.cpp

Complex::operator double()
{
return _num;
}

_num is a field of type double of course

That seems to be okay. The problem is in another class where I actually try to cast a complex object into double. That's my function:

const RegMatrix& RegMatrix::operator *= (double num)
{
    Complex factor(num);
    for(int i=0; i<_numRow; i++)
    {
        for(int j=0; j<_numCol; j++)
        {
            Complex temp = _matrix[i][j];
            _matrix[i][j] = (double) (temp * factor); //<---ERROR HERE
        }
    }
    return *this;
}

That results in invalid cast from type ‘const Complex’ to type ‘double’

I have no clue why it happens. Any ideas? Thanks!


Solution

  • You need to make your operator double a const function:

    operator double() const;
    

    and

    Complex::operator double() const {
        return _num;
    }