我将如何重载这个使用数组的 bigint 类的 + 运算符?C++

How would I overload the + operator for this bigint class which uses arrays? C++

本文关键字:bigint 数组 类的 C++ 运算符 何重载 重载      更新时间:2023-10-16

我目前正在参加使用C++的在线数据结构课程,我正在做一个个人项目来帮助我更好地理解基础知识。我正在从事的项目是bigint类的实现,该类支持使用数组而不是向量或字符串存储和计算任意精度整数。我正在努力实现主要的算术运算符。

数字从最低到最高有效数字存储在数组中(201 将存储为 {1,0,2}),并且计算也按此顺序执行。

我找到了一些与此相关的材料,但绝大多数使用向量/字符串,对我没有多大帮助。其他一些资源,例如这个和这个确实有帮助,但是当我尝试在我的代码中实现它们时不起作用。例如,这段实现加法运算符的代码不起作用,我要么得到bad_alloc异常,要么答案是错误的,但我似乎无法弄清楚为什么或如何解决它,我已经这样做了好几天了:

bigint& operator+(const bigint& lhs, const bigint& rhs){
bool minus_sign = rhs.is_negative();
size_t amt_used = 0;    // to keep track of items in the array
// initial size and size of resulting array
// set initial size to the size of the larger array
// set result_size to ini size plus one in case of carry
size_t ini_size = lhs.get_digit_count() > rhs.get_digit_count() ?
lhs.get_digit_count() : rhs.get_digit_count();
const size_t INITIAL_SIZE = ini_size;
const size_t RESULT_SIZE = INITIAL_SIZE+1;
uint8_t temp[RESULT_SIZE],  // temporary array
result_arr[RESULT_SIZE],
lhs_arr[INITIAL_SIZE], rhs_arr[INITIAL_SIZE]; // new arrays for lhs/rhs of the same size to avoid overflow if one is smaller
//assign corresponding values to the new arrays
for (size_t i = 0; i < lhs.get_digit_count(); i++){
lhs_arr[i] = lhs.get_digit(i);
}
for (size_t i = 0; i < rhs.get_digit_count(); i++){
rhs_arr[i] = rhs.get_digit(i);
}
// perform addition
int carry = 0;  //carry variable
size_t j = 0;
for ( ; j < INITIAL_SIZE; j++){
uint8_t sum = lhs_arr[j] + rhs_arr[j] + carry;
if (sum > 9){
result_arr[j] = sum - 10;
carry = 1;
amt_used++;
}
else{
result_arr[j] = sum;
carry = 0;
amt_used++;
}
}
if (carry == 1){
result_arr[j] = 1;
amt_used++;
}
// flip the array to most sig to least sig, since the constructor performs a switch to least-most sig.
size_t decrement_index = amt_used - 1;
for (int i = 0; i < RESULT_SIZE; i++){
temp[i] = result_arr[decrement_index];
decrement_index--;
}
for (int i = 0; i < RESULT_SIZE; i++){
result_arr[i] = temp[i];
}
// create new bigint using the just-flipped array and return it
bigint result(result_arr, amt_used, minus_sign);
return result;
}

这是我得到的错误:线程 1:EXC_BAD_ACCESS(代码 = 1,地址 = 0x5)

要么这样,要么当我只是添加 8700 + 2100 时,我得到一个非常大的数字

此代码存在几个问题。

VLA 扩展名(用于temp等)的使用不是标准C++。 这些基于堆栈的数组未初始化,因此它们将包含随机数据。 当您用数据填充这些数组时,您不会分配给每个元素。 例如,当左数字短于右数字时,这会导致垃圾结果(以便lhs_arr的几个元素中包含垃圾数据)。 然后,这些错误值将在加法数组中使用。 使用std::vector将符合标准,并导致向量元素全部初始化为适当的内容(如 0)。 这可能是您的"真正大数字"的来源。

当您"翻转阵列"时,如果没有使用所有结果插槽,decrement_index可能是负数。 这可能是您EXC_BAD_ACCESS崩溃的原因。

返回对局部变量的引用会导致未定义的行为,因为当函数返回导致引用悬空时,该局部将被销毁。 这可能是您陈述的任何问题的原因。

你对负数的处理是完全错误的,因为你根本没有真正处理它们。