c++ - BigInteger 类实现重载运算符 '+'

标签 c++ operator-overloading biginteger

我想创建一个在后端使用数组的 bigInteger 类。

BigInt a = 4321; // assume in BigInt class: array is {4,3,2,1}
BigInt b = 2131; // assume in BignInt class: array is {2,1,3,1} 
BigInt sum = a + b; // array {6,4,5,1}

我写了这个函数来重载“+”运算符以将两个数字相加

int* operator+(const uint32& other) const{
    uint32 sum[n];
    for(int i=0; i<n; i++){
        sum[i] = (*this[i]) + other[i];
    }
    return sum;
}

但它不起作用。

注意:假设数组大小是固定的。

My question was not answered in Overload operator '+' to add two arrays in C++ and I made more clarification on this question.

谢谢

最佳答案

直接的问题是您要返回一个指向自动(即函数局部)变量的指针。函数返回时变量超出范围。取消引用返回的指针将导致 undefined behaviour .

我认为该方法的签名应如下所示:

class BigInt {
  BigInt operator+(const BigInt& other) const {...}
  ...
}

换句话说,它应该引用一个 BigInt 的实例,并且应该返回另一个 BigInt 的实例(按值)。

关于c++ - BigInteger 类实现重载运算符 '+',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27645319/

相关文章:

scala - 为什么不围绕整数溢出进行 Scala 设计?

java - 使用 BigInteger 的求和和乘法

c++ - 共享内存访问导致 rss 增加

c++ - 将页面加载到 QWebView 时叠加

c++ - 转换标准 :vector<reference_wrapper<Base>> to std:vector<reference_wrapper<Derived>> Runtime error time: 0 memory: 3412 signal:6

c++ - vector 中存储的表达式的惰性求值

c++ - 递减和取模 - 如何在一行代码中递减负值

c++ - 当重载为类的成员函数时,取消引用运算符 (*) 是如何工作的?

原始类型的 C# 重载运算符

java - 阶乘程序没有给出正确的输出