Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 简单运算符+;我想不通的问题_C++_Math_Operator Overloading - Fatal编程技术网

C++ 简单运算符+;我想不通的问题

C++ 简单运算符+;我想不通的问题,c++,math,operator-overloading,C++,Math,Operator Overloading,我试图添加两个uint8\t列表,就像列表是单个整数一样,我得到了一些奇怪的值: 0x1000+0x100+0x10->0x1210????? 代码如下: // values 0x123456 stored as: {12, 34, 56} integer operator+(integer rhs){ // internal list called 'value' std::list <uint8_t> top = value, bottom = rhs.value

我试图添加两个
uint8\t
列表,就像列表是单个整数一样,我得到了一些奇怪的值:

0x1000+0x100+0x10->0x1210?????

代码如下:

// values 0x123456 stored as: {12, 34, 56}
integer operator+(integer rhs){
    // internal list called 'value'
    std::list <uint8_t> top = value, bottom = rhs.value;
    if (value.size() < rhs.value.size())
        top.swap(bottom);
    top.push_front(0);                           // extra byte for carrying over
    while (bottom.size() + 1 < top.size())       // match up the byte sizes, other than the carry over
        bottom.push_front(0);
    bool carry = false, next_carry = false;
    for(std::list <uint8_t>::reverse_iterator i = top.rbegin(), j = bottom.rbegin(); j != bottom.rend(); i++, j++){
        next_carry = (((uint8_t) (*i + *j + carry)) <= std::min(*i, *j));
        *i += *j + carry;
        carry = next_carry;
    }
    if (carry)
        *top.begin() = 1;
return integer(top);
}
//值0x123456存储为:{12,34,56}
整数运算符+(整数rhs){
//名为“值”的内部列表
标准::列表顶部=值,底部=rhs.value;
if(value.size()下一步是进位=((uint8 t)(*i+*j+进位))考虑当添加两个零位时没有进位时会发生什么情况。
*i+*j+进位==0
,这是
在您的示例中(
0x100+0x10
),以
carry=false
*top.rbegin()=0
,和
*bottom.rbegin()开始=0
。当我们进入循环时,我们会看到以下测试:

next_carry = (((uint8_t) (*i + *j + carry)) <= std::min(*i, *j));
// given *i == 0, *j == 0, and carry == false
// this will evaluate to TRUE

next_-carry=((uint8-t)(*i+*j+carry))设
maxval
uint8-t
的最大值。 确定是否存在下一个进位
,如下所示:

next_carry = false;
if( *i == maxval && ( *j > 0 || carry ) ) // excluding *i + carry > maxval case in next if
        next_carry = true;
    else
        if( *i + carry > maxval - *j ) ///  equal to *i + *j + carry > maxval
             next_carry = true;

next_carry=((*i+*j+carry)>255)
是正确的答案,因为
*i+*j+carry
可以等于最小
std::min(*i,*j)

+1,刚刚得出了相同的结论。从我的答案中删除了
std::min