BigInteger类实现重载运算符'+'(BigInteger Class Implementation Overload operator '+')

编程入门 行业动态 更新时间:2024-10-23 23:28:27
BigInteger类实现重载运算符'+'(BigInteger Class Implementation Overload operator '+')

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

更多推荐

本文发布于:2023-07-30 22:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340361.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   Class   BigInteger   operator   Overload

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!