Question

This C++ Program consists of: operator overloading, as well as experience with managing dynamic memory allocation...

This C++ Program consists of: operator overloading, as well as experience with managing dynamic memory allocation inside a class.

Task

One common limitation of programming languages is that the built-in types are limited to smaller finite ranges of storage. For instance, the built-in int type in C++ is 4 bytes in most systems today, allowing for about 4 billion different numbers. The regular int splits this range between positive and negative numbers, but even an unsigned int (assuming 4 bytes) is limited to the range 0 through 4,294,967,295. Heavy scientific computing applications often have the need for computing with larger numbers than the capacity of the normal integer types provided by the system. In C++, the largest integer type is long, but this still has an upper limit.

Your task will be to create a class, called MyInt, which will allow storage of any non-negative integer (theoretically without an upper limit -- although there naturally is an eventual limit to storage in a program). You will also provide some operator overloads, so that objects of type MyInt will act like regular integers, to some extent. There are many ways to go about creating such a class, but all will require dynamic allocation (since variables of this type should not have a limit on their capacity).

The class, along with the required operator overloads, should be written in the files "myint.h" and "myint.cpp". I have provided starter versions of these files, along with some of the declarations you will need. You will need to add in others, and define all of the necessary functions. Here are the files:

MYINT.H:

// starter file for MyInt class header

class MyInt
{
   // these overload starters are declared as friend functions

   friend MyInt operator+ (const MyInt& x, const MyInt& y);
   // add in multiplication, as well

   friend bool operator< (const MyInt& x, const MyInt& y);
   // add in the other comparison overloads, as well

   // declare overloads for input and output (MUST be non-member functions)
   //  you may make them friends of the class

public:
   MyInt(int n = 0);            // first constructor

   // be sure to add in the second constructor, and the user-defined 
   //  versions of destructor, copy constructor, and assignment operator

private:

   // member data (suggested:  use a dynamic array to store the digits)

};

MYINT.CPP:

#include <iostream>
#include "myint.h"

using namespace std;

int C2I(char c)
// converts character into integer (returns -1 for error)
{
   if (c < '0' || c > '9')        return -1;      // error
   return (c - '0');                            // success
}

char I2C(int x)
// converts single digit integer into character (returns '\0' for error)
{
   if (x < 0 || x > 9)            return '\0';    // error
   return (static_cast<char>(x) + '0');   // success
}

// Add in operator overload and member function definitions 

Details and Requirements

1) Your class must allow for storage of non-negative integers of any (theoretical) size. While not the most efficient in terms of storage, the easiest method is to use a dynamic array, in which each array slot is one decimal "digit" of the number. (This is the suggested technique). You may go ahead and assume that the number of digits will be bound by the values allowed in an unsigned int variable (it would be a good idea to keep track of the number of digits in such a variable). You should create appropriate member data in your class. All member data must be private.

2) There should be a constructor that expects a regular int parameter, with a default value of 0 (so that it also acts as a default constructor). If a negative parameter is provided, set the object to represent the value 0. Otherwise, set the object to represent the value provided in the parameter. There should be a second constructor that expects a C-style string (null-terminated array of type char) as a parameter. If the string provided is empty or contains any characters other than digits ('0' through '9'), set the object to represent the value 0. Otherwise, set the object to represent the value of the number given in the string (which might be longer than a normal int could hold).

Note that the two constructors described above will act as "conversion constructors" (as discussed previously in lecture class). Recall that such constructors will allow automatic type conversions to take place -- in this case, conversions from int to MyInt and from c-style strings to type MyInt -- when appropriate. This makes our operator overloads more versatile, as well. For example, the conversion constructor allows the following statements to work (assuming appropriate definitions of the assignment operator and + overloads described later):

MyInt x = 1234;

MyInt y = "12345";

MyInt z = x + 12;

3) Since dynamic allocation is necessary, you will need to write appropriate definitions of the special functions (the "automatics"): destructor, copy constructor, assignment operator. The destructor should clean up any dynamic memory when a MyInt object is deallocated. The copy constructor and assignment operator should both be defined to make a "deep copy" of the object (copying all dynamic data, in addition to regular member data), using appropriate techniques. Make sure that none of these functions will ever allow memory "leaks" in a program.

4) If you use a dynamic array, you will need to allow for resizing the array when needed. There should never be more than 5 unused array slots left in the array at the end of any public operation.

Operator overloads: (The primary functionality will be provided by the following operator overloads).

5) Create an overload of the insertion operator << for output of numbers. This should print the number in the regular decimal (base 10) format -- and no extra formatting (no newlines, spaces, etc -- just the number).

6) Create an overload of the extraction operator >> for reading integers from an input stream. This operator should ignore any leading white space before the number, then read consecutive digits until a non-digit is encountered (this is the same way that >> for a normal int works, so we want to make ours work the same way). This operator should only extract and store the digits in the object. The "first non-digit" encountered after the number may be part of the next input, so should not be extracted. You may assume that the first non-whitespace character in the input will be a digit. i.e. you do not have to error check for entry of an inappropriate type (like a letter) when you have asked for a number.

Example: Suppose the following code is executed, and the input typed is " 12345   7894H".

MyInt x, y;

char ch;

cin >> x >> y >> ch;

The value of x should now be 12345, the value of y should be 7894 and the value of ch should be 'H'.

7) Create overloads for all 6 of the comparison operators ( < , > , <= , >= , == , != ). Each of these operations should test two objects of type MyInt and return an indication of true or false. You are testing the MyInt numbers for order and/or equality based on the usual meaning of order and equality for integer numbers.

8) Create an overload version of the + operator to add two MyInt objects. The meaning of + is the usual meaning of addition on integers, and the function should return a single MyInt object representing the sum.

9) Create an overload version of the * operator to multiply two MyInt objects. The meaning of * is the usual meaning of multiplication on integers, and the function should return a single MyInt object representing the product. The function needs to work in a reasonable amount of time, even for large numbers. (So multiplying x * y by adding x to itself y times will take way too long for large numbers -- this will not be efficient enough).

10) Create the overloads of the pre-increment and post-increment operators (++). These operators should work just like they do with integers. Remember that the pre-increment operator returns a reference to the newly incremented object, but the post-increment operator returns a copy of the original value (before the increment).

11) Create an overloaded version of the - operator to subtract two MyInt objects. The meaning of - is the usual meaning of subtraction on integers, with one exception. Since MyInt does not store negative numbers, any attempt to subtract a larger number from a smaller one should result in the answer 0. The function should return a single MyInt object representing the difference.

12) Create an overloaded / operator and a % operator for division of two MyInt objects. The usual meaning of integer division should apply (i.e. / gives the quotient and % gives the remainder). Both functions should return their result in a MyInt object.

11) General Requirements:

As usual, no global variables, other than constants

All member data should be private

Use appropriate good programming practices as denoted on previous assignments

Since the only output involved with your class will be in the << overload, your output must match mine exactly when running test programs.

You may NOT use classes from the STL (Standard Template Library) -- this includes class <string> -- as the whole point of this assignment is for you to learn how to manage dynamic memory issues inside of a class yourself, not rely on STL classes to do it for you. You may use standard I/O libraries like iostream and iomanip, as well as the common C libraries, like cstring and cctype

Hints and Tips:

1)  Storage: The suggested storage mentioned above is a dynamic array, in which each array slot represents one digit of the number. There are multiple ways to manage this. One method would be to use an array of integers, another would be an array of characters. Both have advantages and disadvantages. An integer array would be easier for arithmetic calculations, but a character array would be easier for input purposes. You may choose your preference, but remember that an integer digit, like 6, and it's corresponding character representation, '6', are not stored as the same value! '6' is stored with its corresponding character code (usually ASCII).

In case you want to use them (not required), I have provided two functions for converting easily between single digit integers and their corresponding character codes. (These functions are only for use with single digits). You may use them if you like, as long as you cite the source in your comments. These are stand-alone functions (not members of any class). Copies of these functions are already placed in your starter "myint.cpp" file.

int C2I(char c)

// converts character into integer (returns -1 for error)

{

   if (c < '0' || c > '9')      return -1;      // error

   return (c - '0');                            // success

}

char I2C(int x)

// converts single digit integer into character (returns '\0'

for error)

{

   if (x < 0 || x > 9)          return '\0';    // error

   return (static_cast<char>(x) + '0');         // success

}

6) Input: For the >> operator overload, there are some issues to be careful about. You will not be able to just use the normal version of >> for integers, because it attempts to read consecutive digits, until a non-digit is encountered. The problem here is that we will be entering numbers that go beyond the capacity of a normal int (like 6 trillion). So, you will probably find it necessary to read one digit at a time (which means one byte, or character, at a time). Because of this, you may find the above conversion functions useful.

You already know of some istream member functions (like getline), and you have used many versions of the >> operator on basic types. One thing worth keeping in mind is that when the >> operator is used for built-in types, any leading white space is automatically ignored. However, there are a couple of other istream functions you might find useful, including the ones with prototypes:

int get();

int peek();

The get() function extracts and returns the next single character on the stream, even if it is a white space character, like the newline. This function does not skip white space (or any other characters), like the built-in >> functions do. The peek() function just looks at and returns the next character on the stream, but it does not extract it. This function is good for seeing what the next character is (i.e. like whether it is a number or not), without actually picking it up.

7) Comparison Overloads: Writing all 6 comparison overloads may sound like a big task, but it really isn't. Always remember that once a function is written, other functions can call it. For example, once you have written the details of comparing two numbers with the less-than operator, it should be very easy to define the > operator (by calling upon the < operator to do the work). You can't write them ALL this way, because you don't want to get stuck in an infinite loop (i.e. don't make both < and > call each other -- you'll never get out!) But, you can certainly make the job easier by defining some of these in terms of others that are already written.

8) Addition operator: This is a more difficult function than it sounds like, in the MyInt class. However, the algorithm should be conceptually easy -- it can follow exactly the way you learned to add back in grade school! You'll probably find it most helpful to break this algorithm down to the grade school step-by-step level, performing an addition digit by digit. And don't forget that some additions can cause a carry!

9) Multiplication operator: This one will be a little more complex than the addition overload, but again, you should think back to the algorithm you learned for multiplying numbers in grade school. The same algorithm can be applied here. Again, don't forget the carries!

MAIN.CPP SAMPLE FILE:

// main.cpp
//
// Driver program to demonstrate the behavior of the MyInt class
// 
// You can add more tests of your own, or write other drivers to test your
// class

#include <iostream>
#include "myint.h"

using namespace std;

MyInt Fibonnaci(MyInt num);

int main()
{

  // demonstrate behavior of the two constructors and the << overload

  MyInt x(12345), y("9876543210123456789"), r1(-1000), r2 = "14H67", r3;
  char answer;
  cout << "Initial values: \nx = " << x << "\ny = " << y
       << "\nr1 = " << r1 << "\nr2 = " << r2 << "\nr3 = " << r3 << "\n\n";

  // demonstrate >> overload

  cout << "Enter first number: ";
  cin >> x;
  cout << "Enter second number: ";
  cin >> y;

  cout << "You entered:\n";
  cout << "  x = " << x << '\n';
  cout << "  y = " << y << '\n';

  // demonstrate assignment =
  cout << "Assigning r1 = y ...\n";
  r1 = y;
  cout << "  r1 = " << r1 << '\n';

  // demonstrate comparison overloads
  if (x < y) cout << "(x < y) is TRUE\n";
  if (x > y) cout << "(x > y) is TRUE\n";
  if (x <= y)        cout << "(x <= y) is TRUE\n";
  if (x >= y)        cout << "(x >= y) is TRUE\n";
  if (x == y)   cout << "(x == y) is TRUE\n";
  if (x != y)   cout << "(x != y) is TRUE\n";

  // demonstrating + and * overloads
  r1 = x + y;
  cout << "The sum (x + y) = " << r1 << '\n';
  r2 = x * y;
  cout << "The product (x * y) = " << r2 << "\n\n";
  cout << "The sum (x + 12345) = " << x + 12345 << '\n';
  cout << "The product (y * 98765) = " << y * 98765 << '\n';

  // create Fibonacci numbers (stored as MyInts) using +
  cout << "\nAssuming that the Fibonnaci sequence begins 1,1,2,3,5,8,13..."
       << "\n\nThe 10th Fibonnaci number   = " << Fibonnaci(10)
       << "\n\nThe 100th Fibonnaci number  = " << Fibonnaci(100)
       << "\n\nThe 1000th Fibonnaci number = " << Fibonnaci(1000)
       << "\n\nThe 2000th Fibonnaci number = " << Fibonnaci(2000)
       << "\n\n";
}

MyInt Fibonnaci(MyInt num)
{
   MyInt n1 = 1, n2 = 1, n3;
   MyInt i = 2;
   while (i < num)
   {
        n3 = n1 + n2;
        n1 = n2;
        n2 = n3;
        i++;
   }
   return n2;
}

SAMPLE RUN EXAMPLES:

SAMPLE RUN 1:

Initial values: 
x = 12345
y = 9876543210123456789
r1 = 0
r2 = 0
r3 = 0

Enter first number: 987654987654 
Enter second number: 987654987654
You entered:
  x = 987654987654
  y = 987654987654
Assigning r1 = y ...
  r1 = 987654987654
(x <= y) is TRUE
(x >= y) is TRUE
(x == y) is TRUE
The sum (x + y) = 1975309975308
The product (x * y) = 975462374637822892423716

The sum (x + 12345) = 987654999999
The product (y * 98765) = 97545744855647310

Assuming that the Fibonnaci sequence begins 1,1,2,3,5,8,13...

The 10th Fibonnaci number   = 55

The 100th Fibonnaci number  = 354224848179261915075

The 1000th Fibonnaci number = 43466557686937456435688527675040625802564660517371
78040248172908953655541794905189040387984007925516929592259308032263477520968962
3239873322471161642996440906533187938298969649928516003704476137795166849228875

The 2000th Fibonnaci number = 42246963333923048787067256023414827825798528402506
81098010280137314308584370130707224123599639141511088446087538909603607640194711
64359602927198331259873732625355580260699158591522949245390499872225679531698287
44824729922639018337167780606070116154978867198798583114688708762645973690867228
84023654422295243347964480139515349562972087652656069529806499841977448720155612
802665404554171717881930324025204312082516817125

SAMPLE RUN 2:

Initial values: 
x = 12345
y = 9876543210123456789
r1 = 0
r2 = 0
r3 = 0

Enter first number: 123456789123456789123456789123456789
Enter second number: 1010101010101010101010101010101010101
You entered:
  x = 123456789123456789123456789123456789
  y = 1010101010101010101010101010101010101
Assigning r1 = y ...
  r1 = 1010101010101010101010101010101010101
(x < y) is TRUE
(x <= y) is TRUE
(x != y) is TRUE
The sum (x + y) = 1133557799224466890133557799224466890
The product (x * y) = 1247038273974311001247038273974310999987529617260256889987
52961726025689

The sum (x + 12345) = 123456789123456789123456789123469134
The product (y * 98765) = 99762626262626262626262626262626262625265


Assuming that the Fibonnaci sequence begins 1,1,2,3,5,8,13...

The 10th Fibonnaci number   = 55
  
The 100th Fibonnaci number  = 354224848179261915075

The 1000th Fibonnaci number = 43466557686937456435688527675040625802564660517371
78040248172908953655541794905189040387984007925516929592259308032263477520968962
3239873322471161642996440906533187938298969649928516003704476137795166849228875

The 2000th Fibonnaci number = 42246963333923048787067256023414827825798528402506
81098010280137314308584370130707224123599639141511088446087538909603607640194711
64359602927198331259873732625355580260699158591522949245390499872225679531698287
44824729922639018337167780606070116154978867198798583114688708762645973690867228
84023654422295243347964480139515349562972087652656069529806499841977448720155612
802665404554171717881930324025204312082516817125

The following files need to be submitted:

myint.h

myint.cpp

You may take your time, and update me in the comments.

Thanks for your help!

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// main.cpp

#include <iostream>

#include "myint.h"

using namespace std;

MyInt Fibonnaci(MyInt num);

int main()

{

// demonstrate behavior of the two constructors and the << overload

MyInt x(12345), y("9876543210123456789"), r1(-1000), r2 = "14H67", r3;

char answer;

cout << "Initial values: \nx = " << x << "\ny = " << y

<< "\nr1 = " << r1 << "\nr2 = " << r2 << "\nr3 = " << r3 << "\n\n";

// demonstrate >> overload

cout << "Enter first number: ";

cin >> x;

cout << "Enter second number: ";

cin >> y;

cout << "You entered:\n";

cout << " x = " << x << '\n';

cout << " y = " << y << '\n';

// demonstrate assignment =

cout << "Assigning r1 = y ...\n";

r1 = y;

cout << " r1 = " << r1 << '\n';

// demonstrate comparison overloads

if (x < y) cout << "(x < y) is TRUE\n";

if (x > y) cout << "(x > y) is TRUE\n";

if (x <= y) cout << "(x <= y) is TRUE\n";

if (x >= y) cout << "(x >= y) is TRUE\n";

if (x == y) cout << "(x == y) is TRUE\n";

if (x != y) cout << "(x != y) is TRUE\n";

// demonstrating + and * overloads

r1 = x + y;

cout << "The sum (x + y) = " << r1 << '\n';

r2 = x * y;

cout << "The product (x * y) = " << r2 << "\n\n";

cout << "The sum (x + 12345) = " << x + 12345 << '\n';

cout << "The product (y * 98765) = " << y * 98765 << '\n';

// create Fibonacci numbers (stored as MyInts) using +

cout << "\nAssuming that the Fibonnaci sequence begins 1,1,2,3,5,8,13..."

<< "\n\nThe 10th Fibonnaci number = " << Fibonnaci(10)

<< "\n\nThe 100th Fibonnaci number = " << Fibonnaci(100)

<< "\n\nThe 1000th Fibonnaci number = " << Fibonnaci(1000)

<< "\n\nThe 2000th Fibonnaci number = " << Fibonnaci(2000)

<< "\n\n";

}

MyInt Fibonnaci(MyInt num)

{

MyInt n1 = 1, n2 = 1, n3;

MyInt i = 2;

while (i < num)

{

n3 = n1 + n2;

n1 = n2;

n2 = n3;

i++;

}

return n2;

}

==================================================================================

// myint.cpp

#include "myint.h"

#include <iostream>

#include <math.h>

#include <cstring>

#include <stdlib.h>

using namespace std;

// reverseString ---------------------------------------------------------

void reverseString (char *s) {

char t, *d = &(s[strlen (s) - 1]);

while (d > s) {

t = *s;

*s++ = *d;

*d-- = t;

}

}

int C2I(char c)

// converts character into integer (returns -1 for error)

{

if (c < '0' || c > '9'){

return -1; // error

}

return (c - '0'); // success

}

char I2C(int x)

// converts single digit integer into character (returns '\0' for error)

{

if (x < 0 || x > 9){

return '\0'; // error

}

return (static_cast<char>(x) + '0'); // success

}

// newArray() -------------------------------------------------------------

// Container space allocator

char* MyInt::newArray(int space)

{

char* oldArray = 0;

oldArray = new (nothrow) char[space];

if (oldArray == 0)

{

cout << "Failed!\n";

}

else

{

//cout << "Succeeded!\n";

}

return oldArray;

}

// reserve() request container size increase --------------------------------

void MyInt::reserve(int newCapacity){

if(size > newCapacity){

cout << "Error. Setting capacity smaller than current size\n";

exit(EXIT_FAILURE);

}

if(capacity == newCapacity){

return;

}else{

if(capacity > newCapacity){

return;

}else{

char* oldArr = array;

array = newArray(newCapacity);

for(int i=0; i<size; i++){

array[i] = oldArr[i];

}

capacity = newCapacity;

delete [] oldArr;

}

}

}

// first constructor ------------------------------------------------------

// pass in int n and create object with it if >= 0

MyInt::MyInt(int n){

if(n > 0){

int len = 0;

size = len;

int x = n;

while (n > 0) {

n = n / 10;

len++;

}

size = len;

capacity = (len + 5);

array = newArray(capacity);

//5230/10^3

int m = 0;

for(int i = len - 1; i >= 0; i--){

int y = pow(10, i); // y =10^3

int z = x/y; //5620/100 = 56

while(z > 10) {

z = z % 10;

}

char newInt = I2C(z);

array[i] = newInt; // array = ['5', '6', '2', '0']

}

}

else{

size = 1;

capacity = 6;

array = newArray(capacity);

array[0] = '0';

}

}

// second constructor -------------------------------------------------------

MyInt::MyInt(const char str[]){

int length = strlen(str);

char localstr[length];

strcpy(localstr,str);

bool badChars = false;

for(int i=0; i < length; i++){

if(localstr[i] < '0' || localstr[i] > '9'){

badChars = true;

}else{

}

}

if (!badChars){

size = length;

capacity = length + 5;

array = newArray(capacity);

reverseString(localstr);

strcpy(array, localstr);

}else{

size = 1;

capacity = size +5;

array = newArray(capacity);

array[0] = '0';

}

}

// third constructor -------------------------------------------------------

MyInt::MyInt(int size, char fill){

this->size=size;

capacity =size+5;

array = newArray(capacity);

for(int i=0;i<capacity;i++)

array[i] = fill;

}

// copy constructor --------------------------------------------------------

MyInt::MyInt(const MyInt& s){   

size = s.size;

capacity = s.capacity;

array = new char[capacity];

strcpy(array,s.array);

}

// destructor --------------------------------------------------------------

MyInt::~MyInt(){   

if (array != 0){

delete [] array;

}

}

// assignment operator = ---------------------------------------------------

MyInt& MyInt::operator=(const MyInt& s){   

if (this != &s)

{

delete [] array;

size = s.size;

capacity = s.capacity;

array = new char[capacity];

strcpy(array,s.array);

}

return *this;

}

// prefix ++ --------------------------------------------------------------

MyInt MyInt::operator++(){   

size = size + 1;

return *this;

}

// postfix ++ -------------------------------------------------------------

MyInt MyInt::operator++(int){   

MyInt temp = *this;

size = size + 1;

return temp;

}

// addition operator + ----------------------------------------------------

MyInt operator+(const MyInt& x, const MyInt& y){

MyInt s((x.size<y.size)?y:x); //array which is the size of larger of both arrays

int remainder = 0, columnTotal = 0;

int i;

  

for(i = 0; i< s.size; i++){ //iterate from end to begin of array

if(s.size == s.capacity){

s.reserve(2*s.size + 1);

}

int operand1(0);

int operand2(0);

//if the summation is larger than 1 digit

if (i < x.size) {

operand1 = C2I(x.array[i]);

}

if (i < y.size) {

operand2 = C2I(y.array[i]);

}

if((columnTotal = remainder + operand1 + operand2) > 9){

remainder = columnTotal / 10; //store remainder

columnTotal = columnTotal % 10;

}

else {

remainder = 0;

}

char convertChar = I2C(columnTotal);

s.array[i] = convertChar;

}

if(remainder > 0){

if(s.size == s.capacity){

s.reserve(2*s.size + 1);

}

s.size++;

s.array[i] = I2C(remainder);

}

return s;

}

// lshift() ---------------------------------------------------------------

MyInt lshift(MyInt a, int k) { // returns a shifted left by k digits

MyInt c(a);

int i;

for (i = 0; i<a.size ; i++) {

if(c.size == c.capacity){

c.reserve(2*c.size + 1);

}

c[i+k] = a[i];

}

if (k==0) {

c.array[c.size] = '0';

}

else if (k>0){

c.array[0] = '0';

}

c.size++;

int j=3;

return c;

}

// multiplication overload * nested loop fxn---------------------------------

MyInt multiplyOneByMany(const MyInt& x, const char y){

MyInt s(x);

  

  

int remainder = 0, columnTotal = 0;

int i;

for(i = 0; i<x.size; i++){ //iterate from end to begin of array

if(s.size == s.capacity){

s.reserve(2*s.size + 1);

}

//if the summation is larger than 1 digit

if((columnTotal = remainder + C2I(x.array[i])*C2I(y)) > 9){

remainder = columnTotal / 10; //store remainder

columnTotal = columnTotal % 10;

}

else {

remainder = 0;

}

char convertChar = I2C(columnTotal);

s.array[i] = convertChar;

}

  

if(remainder > 0){

if(s.size == s.capacity){

s.reserve(2*s.size + 1);

}

s.size++;

s.array[i] = I2C(remainder);

}

return s;

}

// operator* -----------------------------------------------------------------

MyInt operator*(const MyInt& x, const MyInt& y){

MyInt c(0);

MyInt maxDigitOperand( x.size > y.size ? x : y);

MyInt minDigitOperand( x.size > y.size ? y : x);

  

int i;

for (i = 0; i < minDigitOperand.size; i++) {

if(c.size == c.capacity){

c.reserve(2*c.size + 1);

}

if (C2I(maxDigitOperand.array[i]) != 0) { //if it is zero, nothing to do

c = c + lshift(multiplyOneByMany(maxDigitOperand,minDigitOperand.array[i]), i);

}

}

if (minDigitOperand.size == 1){

c.size--;

}

return c;

}

// less than operator < ------------------------------------------------------

bool operator<(const MyInt& x, const MyInt& y){   

int tempSize = max(x.size, y.size);

  

if(x.size < y.size){

return true;

}

else if(x.size == y.size){

if(x.array[0] < y.array[0]){

return true;

}

else{

return false;

}

}

else{

return false;

}

}

// greater than operator > ---------------------------------------------------

bool operator>(const MyInt& x, const MyInt& y){   

return (y < x);

}

// less than or equal to operator <= ------------------------------------------

bool operator<=(const MyInt& x, const MyInt& y){   

return (x < y || x == y);

}

// greater than or equal to operator >= -------------------------------------

bool operator>=(const MyInt& x, const MyInt& y){   

return (x > y || x == y);

}

// equality operator == -------------------------------------------------------

bool operator==(const MyInt& x, const MyInt& y){   

if (x.size != y.size)

return 0;

for (int i = 0; i < x.size; ++i)

if (x.array[i] != y.array[i])

return 0;

return 1;

}

// not equal operator != ------------------------------------------------------

bool operator!=(const MyInt& x, const MyInt& y){   

return !(x == y);

}

// extraction operator << -----------------------------------------------------

ostream &operator << (ostream &output, const MyInt &m){   

for(int i = m.size-1;i>=0; --i){

output << m.array[i];

}

return output;

}

// insertion operator >> -----------------------------------------------------

istream &operator >> (istream &input, MyInt &m){   

char c;

bool startedReading = false;

int arraySize = 0;

char* oldArray; //increases in size by 1

//each time digit read in

while (true) {

c = input.get();

//skip over leading whitespace

if (c == ' '){

if (startedReading) {

break;

}

else {

continue;

}

}

if (c >= '0' || c <= '9') {

startedReading = true;

arraySize++;

//copy the current digit read in from input

//stream

//create new array that holds one more element

//and copy previously read digits into it

char* emptyArray = m.newArray(arraySize); //2

if (arraySize > 1) {

strcpy(emptyArray, oldArray);

}

oldArray = emptyArray; //1

oldArray[arraySize -1 ] = c;

}

char nextChar = input.peek();

if (nextChar == '\n') {

input.get(); //consume newline

break;

}

if (nextChar < '0' || nextChar > '9'){

break;

}

}

//oldArray at this point contains "12345"

if (arraySize > 0){

m.capacity = arraySize + 5;

m.array = m.newArray(m.capacity);

m.size = arraySize;

reverseString(oldArray);

strcpy(m.array, oldArray);

}

return input;

}

// operator[] - accessor -----------------------------------------------------

char& MyInt::operator[](int index){

if(index >= capacity){

cout << "Accessing out of bounds" << endl;

exit(EXIT_FAILURE);

}else{

return array[index];

}

}

==================================================================================

//myint.h

#include <iostream>

using namespace std;

// starter file for MyInt class header

class MyInt

{

friend MyInt operator+(const MyInt& x, const MyInt& y);

friend MyInt operator*(const MyInt& x, const MyInt& y);

friend MyInt multiplyOneByMany(const MyInt& x, const char y);

friend MyInt lshift(MyInt a, int k);

friend bool operator<(const MyInt& x, const MyInt& y);

friend bool operator>(const MyInt& x, const MyInt& y);

friend bool operator<=(const MyInt& x, const MyInt& y);

friend bool operator>=(const MyInt& x, const MyInt& y);

friend bool operator==(const MyInt& x, const MyInt& y);

friend bool operator!=(const MyInt& x, const MyInt& y);

friend ostream &operator << (ostream &output, const MyInt &m);

friend istream &operator >> (istream &input, MyInt &m);

public:

MyInt(int n = 0); // first constructor

MyInt(const char str[]); // second constructor

MyInt(int size, char fill); // third constructor

MyInt(const MyInt& s); // copy constructor

~MyInt(); // destructor

MyInt& operator=(const MyInt& s); // assignment operator overload

MyInt operator++(); // prefix

MyInt operator++(int); // postfix

char& operator [] (int index); // array accessor

void reserve(int newCapacity);

private:

// member data (suggested: use a dynamic array to store the digits)

int size;

int capacity;

char* array;

char* newArray(int space);

MyInt multiplyOneByMany(const MyInt& x, const char y);

MyInt lshift(MyInt a, int k);

};

===========================================================================

sample output

C:Program Files Dev-CpplProject1.exe Initial values: x = 12345 y9876543210123456789 10 20 r3 =0 Enter first number 9876549876

Add a comment
Know the answer?
Add Answer to:
This C++ Program consists of: operator overloading, as well as experience with managing dynamic memory allocation...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • C++ problem with dynamic arrays is that once the array is created using the new operator...

    C++ problem with dynamic arrays is that once the array is created using the new operator the size cannot be changed. For example, you might want to add or delete entries from the array similar to the behavior of a vector. This project asks you to create a class called DynamicStringArray that includes member functions that allow it to emulate the behavior of a vector of strings. The class should have: A private member variable called dynamicArray that references a...

  • Multiple Choice Multiple Choice Section 4.1 Pointers and Dynamic Memory Consider the following statements: int *p;...

    Multiple Choice Multiple Choice Section 4.1 Pointers and Dynamic Memory Consider the following statements: int *p; int i; int k; i = 42; k = i; p = &i; After these statements, which of the following statements will change the value of i to 75? A. k = 75; B. *k = 75; C. p = 75; D. *p = 75; E. Two or more of the answers will change i to 75. Consider the following statements: int i =...

  • Project 1 - Operator Overloading (FlashDrive 2.0) In C++, many of the keyboard symbols that are...

    Project 1 - Operator Overloading (FlashDrive 2.0) In C++, many of the keyboard symbols that are used between two variables can be given a new meaning. This feature is called operator overloading and it is one of the most popular C++ features. Any class can choose to provide a new meaning to a keyboard symbol. Not every keyboard letter is re-definable in this way, but many of the ones we have encountered so far are like +, -, *, /,...

  • C++ assignment help! The instructions are below, i included the main driver, i just need help...

    C++ assignment help! The instructions are below, i included the main driver, i just need help with calling the functions in the main function This assignment will access your skills using C++ strings and dynamic arrays. After completing this assignment you will be able to do the following: (1) allocate memory dynamically, (2) implement a default constructor, (3) insert and remove an item from an unsorted dynamic array of strings, (4) use the string class member functions, (5) implement a...

  • How do i Overload the & operator to concatenate two arrays?, so elements from both arrays...

    How do i Overload the & operator to concatenate two arrays?, so elements from both arrays will be seen Below is code i have so far. everything works except the operator overload of &. The & operator only works when both array are equal, first array smaller then second, fails when first array is the largest. class smartArray{ public: int *elements; // dynamic array, memory is allocated in the constructor. Use *this to access size member. int length(); // returns...

  • please help with the operator overloading lab (intArray) in c++ will provide what it is being...

    please help with the operator overloading lab (intArray) in c++ will provide what it is being required and the code that was given from the book. the code that was provided is below ------------------------------------------------------------------------------------------------------------------------- // iadrv.h #ifndef _IADRV_H #define _IADRV_H #include "intarray.h" int main(); void test1(); void test2(); void test3(); void test4(); void test5(); void test6(); void test7(); void test8(); void test9(); void test10(); void test11(); void test12(); void test13(); void test14(); void test15(); void test16(); void test17(); void test18();...

  • Write a code in C++ by considering the following conditions :- Tasks :- 1. Create a...

    Write a code in C++ by considering the following conditions :- Tasks :- 1. Create a class Employee (with member variables: char * name, int id, and double age). 2. Create a constructor that should be able to take arguments and initialize the member variables. 3. Create a copy constructor for employee class to ensure deep copy. 4. Create a destructor and de allocate the dynamic memory. 5. Overload the assignment operator to prevent shallow copy and ensure deep copy....

  • Overview This checkpoint is intended to help you practice the syntax of operator overloading with member...

    Overview This checkpoint is intended to help you practice the syntax of operator overloading with member functions in C++. You will work with the same money class that you did in Checkpoint A, implementing a few more operators. Instructions Begin with a working (but simplistic) implementation of a Money class that contains integer values for dollars and cents. Here is my code: /********************* * File: check12b.cpp *********************/ #include using namespace std; #include "money.h" /**************************************************************** * Function: main * Purpose: Test...

  • IN c++ i post this question 5 times. hope this time somebody answer.. 16.5 Homework 5...

    IN c++ i post this question 5 times. hope this time somebody answer.. 16.5 Homework 5 OVERVIEW This homework builds on Hw4(given in bottom) We will modify the classes to do a few new things We will add copy constructors to the Antique and Merchant classes. We will overload the == operator for Antique and Merchant classes. We will overload the + operator for the antique class. We will add a new class the "MerchantGuild." Please use the provided templates...

  • This Program should run in C++ In an effort to develop in-depth knowledge of base class, derived class, and operator overloading, we will expand on our in-class exercise of developing the rectangleTyp...

    This Program should run in C++ In an effort to develop in-depth knowledge of base class, derived class, and operator overloading, we will expand on our in-class exercise of developing the rectangleType class and overload the following operators: +, -, *, ++, --, ==, !=, >>, and <<. Your program should contain the following features: a. Create a base class named rectangleType with following private data members: • length with double type • width with double type b. rectangleType class...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT