我想创建一个在后端使用数组的 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/