对象要双重转换错误

Object to double conversion error

本文关键字:转换 错误 对象      更新时间:2023-10-16

我试图通过超载双转换操作员来编写一个对象为大整数程序的双转换器。为此,我将大整数转换为一个字符串,然后使用STOD函数将其转换为double。这是函数的副本:

BigInteger::operator double () {
    std::string *str = new std::string[this->m_digitCount];
    for (int j = 0; j < this->m_digitCount; j++) {
        str[j] = this->getDigit(j);
    }
    double a = std::stod(*str);
    return a;
}

只是为了澄清m_digitCount是给定对象中的数字数。

当我运行该程序时,它会崩溃,并说'Abort()被调用。'

我插入了一个断点,发现该程序崩溃了

double a = std::stod(*str)

发生这种情况时,它说

indist4中的0x00007FFB1DEF7788的未经处理的异常 - big integer.exe:Microsoft C 例外:STD :: Invalid_argument在存储器位置0x0000000043f48fdd780。

有人可以帮我找到问题吗?非常感谢。

这不做您认为的事情:

std::string *str = new std::string[this->m_digitCount];

分配一系列空字符串。我不知道您的代码甚至是如何编译的。

无论如何,您的意思是:

std::string str;
str.reserve( m_digitCount );
for (int j = 0; j < m_digitCount; j++) {
    str.push_back( getDigit(j) );
}
return std::stod(str);

请注意,数字应该是字符类型。如果仅是一个从0到9的整数,则必须执行str.push_back( '0' + getDigit(j) )