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 f开发者_JAVA技巧unction:
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!
You need to make your operator double
a const
function:
operator double() const;
and
Complex::operator double() const {
return _num;
}
As the error clearly states, the is no conversion to double for a const Complex. Simply define your conversion operator like this:
operator double() const;
Complex::operator double() const
{
return _num;
}
Note the const modifier at the end. You should really look for information on const-correctness in C++.
精彩评论