I am currently doing a school assignment (I am sorry that my question is about my assignment, but I am not asking about the algorithms used in the codes). I am now currently doing the arithmetic part, addition and subtract. Since there are only two operators, there are 8 combinations of operation. In my program, I can do these four cases:
(+a)+(+b) (-a)+(-b) (-a)-(+b) (+a)-(-b)
However, I cannot figure out the way to do the other four cases, I.e.
(+a)+(-b) (-a)+(+b) (-a)-(-b) (+a)-(+b)
I sincerely hope that you guys can provide suggestions and advice on how to deal with these four cases.
Here is my code:
linkedListType.h: It is a common linked list header file therefore I don't post the whole code here.
bigInteger.h: The functions in this are quite long. Therefore, I skipped posting them out.
#ifndef BIG_INTEGER_H #define BIG_INTEGER_H #include <stack> #include <iostream> #include "linkedListType.h" using namespace std; class bigInteger { private: int sign; // set 0 for positive, 1 for negative linkedListType<int> digits; // internal linked-list for storing digits in reverse order public: bigInteger(); // default constructor bigInteger(const bigInteger& other); // copy constructor // Overload constructor // Use an numerical string to construct this bigInteger // For negative number, the first char in the string is '-' // e.g. "-12345" bigInteger(const string& number); // overload the assignment operator const bigInteger& operator= (const bigInteger& other); // Return a new bigInteger that is equal to *this + other // The contents of this and other should not be modified bigInteger& operator+ (bigInteger& other); // Return a new bigInteger that is equal to *this - other // The contents of this and other should not be modified bigInteger& operator- (bigInteger& other); // Print a big integer // Since the digits are stored in reverse order in the internal // list, you should print in reverse order // Print "undefined" if the digits list is empty friend ostream& operator<<(ostream& os, bigInteger& n); };
bigInteger& operator+ (bigInteger& other);butbigInteger operator+(const bigInteger& other);i.e. return by value and take the argument byconstreference. You may want to writebigInteger& operator+=(const bigInteger& other);(andoperator-=), then you can write+as a non-member function like this:bigInteger operator+(bigInteger lgs, const bigInteger& rhs) { return lhs += rhs; }.friend ostream& operator<<(ostream& os, bigInteger& n);should takeconst bigInteger& n.bigInteger x;and write-x, if there's no "left hand side" to subtractxfrom, the compiler will look for abigInteger bigInteger::operator-()function and call that - it should return the negation of*this- that's explained at the linked question above.+=and-=add and subtract an amount from the value on the left hand side, sox = x + 3can be conveniently shortened tox += 3if the operators are implemented "normally". If you're writing+and-people will kind of expect+=and-=too.