Hello all, I have been getting great advice from the Beginners forum, but it seems this program that I am working on will require more than beginners' help now. I am, hopefully, almost done with this program, but just need a little help with the last part. The program asks the user to input a big natural number, which is inputted as a string. Then the string is converted to an integer and stored in a vector in blocks of 8 starting from the end. For example: s="1234567891011", then vec[0]=67891011 and vec[1]=12345. The user will input another big natural number and the same thing will happen.
This is where my problem starts. I need to add both the inputted numbers and then output them as a string. I need to add the operator+ method somewhere in my Big_Nat class, but I'm not sure how to do so. Here is what I have so far:
After a bit of research, it seems that I need to add:
Big_Nat & operator+(const Big_Nat &rhs);
into the public section of my Big_Nat class. Is this correct? Also, what would I need to do to the implementation file so that it works? Any help at all will be appreciated.
That seems to be much easier said than done. Is there a way to overload the operator+ so I can add the two numbers, which are of type Big_Nat? I have been researching for a long time, and I just can't seem to figure it out...
In general, for a user-defined type T, consider implementing operator+ as a nonmember (non-friend) and in terms of operator+=. For example:
1 2 3 4 5 6
const T operator+( const T & lhs, const T & rhs )
{
T t( lhs );
t += rhs;
return t;
}
Non-friends do not compromise encapsulation and nonmembers provide associativity. The return is by value, such that the arguments remain unchanged, and constant, to prevent it from being used as an lvalue.
In general, for a user-defined type T, consider implementing operator+ as a nonmember (non-friend) and in terms of operator+=
Depending on usage, there will be times where we need to have friend function. E.g I allow int + MyClass in this order and also MyClass + int in this order too.
If using non-friend function, may I know how to build logic like int + MyClass ? I.e the int variable is on the lhs of MyClass.
If addition is commutative (lhs+rhs) == (rhs+lhs). You can just make a wrapper.
Or if you consider that an int can be treat as an object of your class, make a constructor. (like in strings).
You can still avoid friends, if you provide methods in your class
(Note that private inheritance is preferred because boost declares all the remaining functions
as friends, and you probably don't want people doing polymorphic upcasts to
boost::ordered_euclidean_ring_operators<MyBigInt> and such).
If you implement the above methods, then you should get all other permutations for free
(through the inheritance) that allow operation on two MyBigInts or a MyBigInt and an int.