我想创建一个在后端使用数组的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; }但它不起作用。
注意 :假设要修复的数组大小。
我在Overload运算符'+'中没有回答我的问题, 在C ++中添加两个数组 ,我对这个问题做了更多澄清。
谢谢
I want to create a bigInteger class that uses arrays in backend.
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}I wrote this function to overload '+' operator to add the two numbers
int* operator+(const uint32& other) const{ uint32 sum[n]; for(int i=0; i<n; i++){ sum[i] = (*this[i]) + other[i]; } return sum; }but it doesn't work.
Note: assume the array size to be fixed.
My question was not answered in Overload operator '+' to add two arrays in C++ and I made more clarification on this question.
Thank you
最满意答案
当前的问题是你正在返回一个指向自动(即函数本地)变量的指针。 函数返回时,变量超出范围。 取消引用返回的指针会导致未定义的行为 。
我认为该方法的签名应如下所示:
class BigInt { BigInt operator+(const BigInt& other) const {...} ... }换句话说,它应该引用BigInt一个实例,并且应该返回另一个BigInt实例(按值)。
The immediate problem is that you're returning a pointer to an automatic (i.e. function-local) variable. The variable goes out of scope the moment the function returns. Dereferencing the returned pointer would lead to undefined behaviour.
I would argue that the method's signature should look like this:
class BigInt { BigInt operator+(const BigInt& other) const {...} ... }In other words, it should take a reference to an instance of BigInt and should return another instance of BigInt (by value).
更多推荐
发布评论