我想创建一个在后端使用数组的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 operator '+' to add two arrays in C++我的问题没有回答,我对这个问题做了更多的澄清。
谢谢
答案 0 :(得分:3)
当前的问题是你返回一个指向自动(即函数 - 本地)变量的指针。函数返回时,变量超出范围。取消引用返回的指针将导致undefined behaviour。
我认为该方法的签名应如下所示:
class BigInt {
BigInt operator+(const BigInt& other) const {...}
...
}
换句话说,它应该引用BigInt
的实例,并且应该返回BigInt
的另一个实例(按值)。
答案 1 :(得分:1)
// friend_artih_op.cpp (cX) 2014 adolfo.dimare@gmail.com
// http://stackoverflow.com/questions/27645319/
/*
I like arithmetic operators to be 'friend' functions instead of 'class
members' because the compiler will automatically insert invocations to
construct a class value from literals, as it happens inside the
'assert()' invocations in this program.
*/
/// A small 'fake' arithmetic class
class arith {
private:
long * m_ptr; ///< pointed value
public:
arith( long val=0 )
{ m_ptr = new long; *m_ptr = val; }; ///< Default constructor.
arith( const arith& o )
{ m_ptr = new long;
*m_ptr = *(o.m_ptr); } ///< Copy constructor.
~arith( ) { if (0!=m_ptr) { delete m_ptr; } } ///< Destructor.
// operator long() const { return *m_ptr; } ///< Get stored value.
long to_long() const { return *m_ptr; } ///< Get stored value.
friend arith operator+( const arith left , const arith right );
friend bool operator==( const arith left , const arith right );
};
inline arith operator+( const arith left , const arith right ) {
long res = *(left.m_ptr) + *(right.m_ptr);
// 'new long' will be called within the copy constructor
return arith( res );
} ///< letf+rigth
inline bool operator==( const arith left , const arith right ) {
return ( *(left.m_ptr) + *(right.m_ptr) );
} ///< letf==rigth ???
#include <cassert> // assert()
int main() {
arith four(4);
assert( arith(6) == 2+four ); // 2 gets converted to arith(2)
assert( (6) == (2+four).to_long() );
// If you make 'operator+()' a member function, you would not have the
// compiler do the conversion (and you have to do it yourself):
assert( arith(6) == arith(2)+four );
}
// EOF: friend_artih_op.cpp