简体   繁体   English

重载的类型转换不起作用

[英]Overloaded typecasts don't work

I've built a little class representing a decimal number, called Complex. 我建立了一个表示十进制数字的小类,称为Complex。 I want to be able to cast it to double, so here's my code 我希望能够将其转换为两倍,所以这是我的代码

Complex.h Complex.h

public:
    operator double();

Complext.cpp Complext.cpp

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

_num is a field of type double of course _num是类型为double的字段

That seems to be okay. 看来还可以。 The problem is in another class where I actually try to cast a complex object into double. 问题出在另一类中,我实际上尝试将一个复杂的对象转换为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' 这导致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函数:

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. 正如错误明确指出的那样, 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. 注意最后的const修饰符。 You should really look for information on const-correctness in C++. 您应该真正寻找有关C ++中const正确性的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM