Question

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 +, -, *, /, >and <for example. It is a class’ choice to do this, so mostly it is viewed as a driver code convenience to support them.

But because so many of us have an assumption that +should do addition but also perform string concatenation when working with textual data. Each operator becomes a friendfunction in C++ that your class can implement. The arguments to most of the operator overloads are defined as const FlashDrive &. This syntax is a new kind of parameter passing called const-reference parameters.

For a class type, like FlashDrive, const &signifies a read-only argument that cannot be changed by the function that receives this object. The compiler enforces this restriction and, for classes, const &simulates a pass-by-value mechanism without the overhead of copying the object, which might take a tremendous amount of time away from our program. Read the book and demo source examples carefully to see how this is done. Trust me, the first time you work with operators in C++, it is a very error-prone process. My best advice to you is to complete one operator at a time.

Flashdrive 2.0

Rules of the flashdrive comparisons:

  1. The addition operator ( +) combines two flashdrives by created a new flashdrive that has the larger capacity of the two operand flashdrives (e.g. if you have a 20GB flash drive and add it to a 10GB flashdrive, the resulting flashdrive has 20GB of space, not 10GB - capacity is the max()operation). Then, the operator should mark that the new flash drive has used the sum of the two operand’s flashdrives (for instance, if one of the operands used 5GB and the other used 12GB, the resulting flashdrive has used 17GB).
  2. The subtraction operator ( -) substracts two flashdrives by created a new flashdrive that has the larger capacity of the two operand flashdrives (e.g. if you have a 20GB flash drive and subtract a 10GB flashdrive, the resulting flashdrive has 20GB of space, not 10GB - capacity is the max()operation). Then, the operator should remove the right operand’s storage from the left operand (for instance, if the left operand has used 20GB and the other used 12GB, the resulting flashdrive has used 8GB).
  3. The less than operator ( <) should compare the if the left operand’s storage used is less than the right operand’s storage used.
  4. The greater than operator ( >) should compare the if the left operand’s storage used is greater than the right operand’s storage used.

Using flashdrive_2_0.cpp, enhance the FlashDriveclass so that it supports the operators +, -, <and >. A sample pile of driver code is shown below to assist you in this effort. Operators +and -should create a new FlashDrivefrom the two arguments by combining their contents. If you wind up with a FlashDrivewith a value stored that exceeds its capacity, print out an error message. If you wind up with a negative capacity or storage value, print out an error message. Operators <and >must return booland should compare the holdings of the two arguments to determine which one is bigger.

My strong advice is to work one operator at a time, as these steps are very error-prone and lead to many, many compile errors.

Finally, I would also like you to place FlashDrivein namespace cs52which will affect the resulting driver code as well as the class’ .hand .cppfiles. * Note:your code will not compile until you define the cs52namespace

FlashDrive 2.0

FlashDrive( );
FlashDrive( int capacity, int used, bool pluggedIn );

void plugIn( );

bool isPluggedIn( );
void pullOut( );

void writeData( int amount );
void eraseData( int amount );

void formatDrive( );

void setCapacity( int amount );
void setUsed( int amount );

int getCapacity( );
int getUsed( );

Sample Driver Code

cs52::FlashDrive drive1( 10, 0, false );
cs52::FlashDrive drive2( 20, 0, false );
    
drive1.plugIn( );
drive1.formatDrive( );
drive1.writeData( 5 );
drive1.pullOut( );

drive2.plugIn( );
drive2.formatDrive( );
drive2.writeData( 1 );
drive2.pullOut( );

cs52::FlashDrive combined = drive1 + drive2;
cout << "this drive's filled to " << combined.getUsed(
) << endl;
cout << "this drive's capacity is " <<
combined.getCapacity() << endl;

cs52::FlashDrive other = drive1 - drive2;
cout << "the other drive's filled to " <<
other.getUsed( ) << endl;
cout << "the other drive's capacity is " <<
other.getCapacity() << endl;

if (combined > other) {
    cout << "looks like combined is bigger..." << endl;
}
else {
    cout << "looks like other is bigger..." << endl;
}

if (drive2 > other) {
    cout << "looks like drive2 is bigger..." << endl;
}
else {
    cout << "looks like other is bigger..." << endl;
}

if (drive2 < drive1) {
    cout << "looks like drive2 is smaller..." << endl;
}
else {
    cout << "looks like drive1 is smaller..." << endl;
}

Sample Output

this drive's filled to 6 
this drive's capacity is 20 
the other drive's filled to 4 
the other drive's capacity is 20 
looks like combined is bigger... 
looks like other is bigger... 
looks like drive2 is smaller...
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here I am providing the code. Hope it helps.

Driver.cpp

#include <iostream>
#include <stdexcept>
#include "TrashCan.h"
#include <cstdlib>
using namespace std;
using namespace cs52;
int main( ) {
  
   cout << "Welcome to Howie's TrashCan Program!" << endl;


   TrashCan myCan;
   TrashCan yourCan;
   TrashCan empty( 0, 0 );
   yourCan.setSize( 12 );
   myCan.setSize( 12 );
yourCan.addItem( );
   yourCan.addItem( );
   myCan.addItem( );
   myCan.printCan();
   yourCan.printCan();

   // read in a TrashCan...
   // the class designer for TrashCan (that's you!)
   // gets to decide which fields matter and should be read in
   cs52::TrashCan sample;
   cin >> sample;

   // print out a TrashCan...
   // the class designer for TrashCan (that's you!)
   // gets to decide which fields matter and should be printed
   cout << sample << endl;


   TrashCan combined = yourCan + myCan;
   cout << "this drive's filled to " << combined.getUsed( ) << endl;


   TrashCan other = combined - myCan;
cout << "the other cup's filled to " << other.getUsed( ) << endl;


   if (combined > other) {
     cout << "looks like combined is bigger..." << endl;
   }
   else {
     cout << "looks like other is bigger..." << endl;
   }


   if (myCan > other) {
     cout << "looks like myCan is bigger..." << endl;
   }
   else {
     cout << "looks like other is bigger..." << endl;
   }

   if (yourCan < myCan) {
     cout << "looks like yourCan is smaller..." << endl;
   }
   else {
     cout << "looks like myCan is smaller..." << endl;
   }

   // let's throw some exceptions...

   try {
     empty = empty - combined;
     cout << "something not right here..." << endl;
   } catch( exception &e ) {
   cout << e.what() << endl;// an exception should get thrown...
   cerr << "Type: " << typeid( e ).name( ) << endl;// so the lines of code here should
     // be run, not the cout statement above...
   cout << "underflowing exception was caught. moving on... " << endl;
   } catch( std::logic_error ) {
     // the new kind of exception should be caught, not this one
     cout << "wrong kind of exception caught..." << endl;
   }

   try {
     empty.addItem( );
     cout << "something not right here..." << endl;
   } catch( exception &e ) {
    cout << e.what( ) << endl ; // an exception should get thrown...
     // so the lines of code here should
     // be run, not the cout statement above...


     cout << "overflowing exception was caught. moving on... "<< endl;
   } catch( std::logic_error ) {
     // the new kind of exception should be caught, not this one
     cout << "wrong kind of exception caught..." << endl;

   }

   try {
     cs52::TrashCan t( -1, -1 );
     cout << "something not right here..." << endl;
   } catch( exception &e ) {
      cout << e.what() << endl;
   cerr << "Type: " << typeid( e ).name( ) << endl;// an exception should get thrown...
     // so the lines of code here should
     // be run, not the cout statement above...
     cout << "underflowing exception was caught. moving on... " << endl;


   } catch( std::logic_error ) {
     // the new kind of exception should be caught, not this one
     cout << "wrong kind of exception caught..." << endl;
   }
  
   return( 0 );
}

Trashcan.cpp

#include <iostream>
#include <stdexcept>
#include "TrashCan.h"
#include <cstdlib>
using namespace std;

namespace cs52 {
TrashCan::TrashCan( ) {
  myIsCovered = false;
  my_Size = 0;
  my_Contents = 0;
}


TrashCan::TrashCan( int size ) {
  if (size < 0 )
  {
   throw ;
  }
  myIsCovered = false;
  my_Size = size;
  my_Contents = 0;
}


TrashCan::TrashCan( int size, int contents ) {
  if (size < 0 || contents < 0)
  {
   throw UnderflowingTrashCanException(size, contents);
  }
  myIsCovered = false;
  my_Size = size;
  my_Contents = contents;


}

void TrashCan::setSize( int size ) {
  my_Size = size;
}

void TrashCan::addItem( ) {
  if (my_Size< 0 || my_Contents< 0)
  {
   throw UnderflowingTrashCanException(my_Size, my_Contents);
  }
  my_Contents = my_Contents + 1;
}
  
void TrashCan::empty( ) {
  my_Contents = 0;
}


void TrashCan::cover( ) {
myIsCovered = true;
}


void TrashCan::uncover( ) {
  myIsCovered = false;
}


void TrashCan::printCan( ) {
  cout << "A TrashCan with a size=" << my_Size << " and containing " << my_Contents << " piece";
  if (my_Contents != 1) {
   cout << "s";
  }
  cout << " of trash" << endl;
}


/************error checking***********/


int TrashCan::getUsed( ){
  if (my_Contents > 0)
   if (my_Contents > my_Size)
   {
    return 0;
    
   }else if (my_Contents == my_Size)
   {
    return 1;
    
   }
   else
  {
    return 2;
   }
  else
  {
   return 3;
   
  }
   }

/************overloading operators***********/
TrashCan operator+ (const TrashCan& can1, const TrashCan& can2){
  TrashCan temp;
  temp.my_Contents = can1.my_Contents + can2.my_Contents;

//throwing negative value exception
  if (temp.my_Contents < 0 || temp.my_Size < 0 || can1.my_Contents < 0 || can1.my_Size <0 || can2.my_Contents < 0 || can2.my_Size < 0)
{
   //throw UnderflowingTrashCanException();
  }


//checking if pointer to object is null
  if (&temp == NULL)
  {
   throw logic_error("Your trashcan cannot be NULL!");
  }

//use the largest trashcan size
  if(can1.my_Size > can2.my_Size)
   temp.my_Size = can1.my_Size;
  else
   temp.my_Size = can2.my_Size;


  //checking for size vs. contents
  if(temp.myIsCovered > temp.my_Size){
   throw OverflowingTrashCanException(temp.my_Size, temp.my_Contents);
  }
  
  return temp;
}


TrashCan operator -(const TrashCan& can1, const TrashCan& can2){
  TrashCan temp;
  temp.my_Contents = can1.my_Contents - can2.my_Contents;
//throwing negative value exception
  if (temp.my_Contents < 0 || temp.my_Size < 0
   || can1.my_Contents < 0 || can1.my_Size <0
   || can2.my_Contents < 0 || can2.my_Size < 0)
  {
   throw UnderflowingTrashCanException(temp.my_Size, temp.my_Contents);
  }
  //checking if pointer to object is null
  if (&temp == NULL)
  {
   throw logic_error("Your trashcan cannot be NULL!");
  }


  //use the larges trashcan size
  if(can1.my_Size > can2.my_Size)
   temp.my_Size = can1.my_Size;
  else
   temp.my_Size = can2.my_Size;


  //checking for size vs. contents
  if(temp.myIsCovered > temp.my_Size){
   throw OverflowingTrashCanException(temp.my_Size, temp.my_Contents);
  }


  return temp;

  
}


bool operator <(const TrashCan& can2, const TrashCan& can3){
  //checking if pointer to object is null
  if (&can2== NULL || &can3 == NULL)
  {
   throw logic_error("Your trashcan cannot be NULL!");
  }


  if(can2.my_Contents < can3.my_Contents)
   return true;
else
   return false;
}

bool operator >(const TrashCan& can1,const TrashCan& can2){
  //checking if pointer to object is null
  if (&can1 == NULL|| &can2 == NULL)
  {
   throw logic_error("Your trashcan cannot be NULL!");
  }
  if(can1.my_Contents > can2.my_Contents)
   return true;
  else
   return false;
}

ostream& operator <<(ostream& outs, TrashCan& can ){
  
  switch (can.getUsed())
  {
  case 0:{


   return (outs << "the brim and is spilling out"); break;}
  case 1:
   return (outs << "the brim"); break;
  case 2:
   return (outs << can.my_Contents << " pieces of trash"); break;
case 3:
   return (outs << "negative number? It's a black hole! RUN!"); break;
  }
}

//overloading ostream with the option to check for NUll pointers
ostream& operator <<(ostream& outs, const TrashCan* drive){
  try{
   if (drive == NULL)
   {
    throw logic_error("You cannot have null trashcan!");
   }
   return (outs << "The size is " << drive->my_Size << endl
   << "There are " << drive->my_Contents << " pieces of trash" << endl);
}catch( logic_error &e){
   cout << e.what() << endl;
   drive = new TrashCan(0,0);
  }
}

istream& operator >>(istream& in, TrashCan& can){
  cout << "Size: ";
  in>> can.my_Size;
  cout << "Contents: ";
  in >> can.my_Contents;
  return in;
}

//overloading istream operators, if pointer to object is null, create one.
istream& operator >>(istream& in, TrashCan * &drive){
  try{
   if (drive == NULL)
   {
    throw logic_error("Your trashcan cannot be NULL!");
   }
    cout << "Size: ";
    in >> drive->my_Size;
   cout << "Contents: ";
    in >> drive->my_Contents;
    if (drive->my_Contents < 0 || drive->my_Size < 0 )
    {
     throw UnderflowingTrashCanException(drive->my_Size, drive->my_Contents);
    }else

    return in;
   
   
  }catch(logic_error &e){
   cout << e.what() << endl;
   cout << "restoring default parameter" << endl;
   drive = new TrashCan(0,0);
  }

}
}

TrashCan.h


#ifndef TRASHCAN_H
#define TRASHCAN_H
#include <iostream>
#include <cstdlib>


using namespace std;


namespace cs52{
class TrashCan {
public:


  TrashCan( ); // object trashcan
  TrashCan( int size ); //object trashcan with specific size
  TrashCan( int size, int contents ); //object trashcan with specific size and content

  void setSize( int size ); //set the size of the transh
  void addItem( ); //add item to the trashcan
  void empty( ); //inform the user the trash can is empty
  void cover( ); //what to do when the lid is on
  void uncover( ); // what to do when the lid is off
  void dirty( ); //what to do when the trash can is dirty
  void notDirty( ); //what to do when the trash can is not dirty
  void removeItem( ); //remove item from the trash can
  void full( ); //what to do when the trash can is full




  void printCan( ); //display the trash can


  int getUsed( );//returns a value to varify which output error/contents
  
  friend ostream& operator <<(ostream& outs, TrashCan& can );//handles output of object trashCan
  friend istream& operator >>(istream& in, TrashCan& can);//takes the trashcan's content and size
  friend TrashCan operator +(const TrashCan& my_Size1, const TrashCan& my_Size2);
  friend TrashCan operator -(const TrashCan& my_Size1, const TrashCan& my_Size2);
  friend bool operator <(const TrashCan& my_Contents1,const TrashCan& my_Contents2);
  friend bool operator >(const TrashCan& my_Contents1, const TrashCan& my_Contents2);


  //pointers handling
  friend std::ostream& operator <<( std::ostream& outs, const TrashCan * drive );
  friend std::istream& operator >>( std::istream& ins, TrashCan * & drive );
private:
  bool myIsCovered; //a boolean value that determines if the lid is on or not
  bool my_Trash_Dirty;// a boolean value that determines if the trash can is dirty
  bool my_Trash; //a boolean value that determines if the trash can is full
  int my_Size; //a specific size of the trash can
  int my_Contents; //a specific content in the trash can

};


}
#endif

Thank you. Please like.

Add a comment
Know the answer?
Add Answer to:
Project 1 - Operator Overloading (FlashDrive 2.0) In C++, many of the keyboard symbols that are...
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
  • Help please with a Project in C++ In C++, many of the keyboard symbols that are used between two ...

    Help please with a Project in C++ 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 +, -, *, /,...

  • I have provided you with a sample class named FlashDrive which has been diagrammed below. Using...

    I have provided you with a sample class named FlashDrive which has been diagrammed below. Using the FlashDrive class provided earlier, upgrade the class so that it supports various operators. Make operator+ combine together the contents of two FlashDrive, as long as the contents does not exceed the size. Make operator- subtract one FlashDrive contents from another, as long as the size or contents don't go negative. Support the >> and << operators to allow instances to be read from...

  • Background: This assignment deals with inheritance. Inheritance is one of the major principles of object-oriented programming....

    Background: This assignment deals with inheritance. Inheritance is one of the major principles of object-oriented programming. In C++, one of the biggest goals is "code reuse". Inheritance accomplishes this. In order to get inheritance working in C++, you must get both the structure of your .h files as well as the implementation of your constructor correct. Constructor implementations must use an initialization list. Please review the book and the online content on these issues so you know how it works...

  • Please zoom in so the pictures become high resolution. I need three files, FlashDrive.cpp, FlashDrive.h and...

    Please zoom in so the pictures become high resolution. I need three files, FlashDrive.cpp, FlashDrive.h and user_main.cpp. The programming language is C++. I will provide the Sample Test Driver Code as well as the codes given so far in text below. Sample Testing Driver Code: cs52::FlashDrive empty; cs52::FlashDrive drive1(10, 0, false); cs52::FlashDrive drive2(20, 0, false); drive1.plugIn(); drive1.formatDrive(); drive1.writeData(5); drive1.pullOut(); drive2.plugIn(); drive2.formatDrive(); drive2.writeData(2); drive2.pullOut(); cs52::FlashDrive combined = drive1 + drive2; // std::cout << "this drive's filled to " << combined.getUsed( )...

  • Background: The purpose of this assignment is to practice dealing with exception handling and textual data....

    Background: The purpose of this assignment is to practice dealing with exception handling and textual data. Exception handling is a very important part of being an object-oriented programming. Rather returning some kind of int return value every time you tickle an object, C++ programmers expect methods to focus on their task at hand. If something bad happens, C++ programmers expect methods to throw exceptions. When caught, exceptions can be processed. When uncaught, they cause a program to terminate dead in...

  • Project 2 - Flashdrive 1.0 I have provided you with a sample class named FlashDrive which...

    Project 2 - Flashdrive 1.0 I have provided you with a sample class named FlashDrive which has been diagrammed below and described in the online course content. For this unit, I'd like you to identify additional member variables (data) that would be appropriate for the class FlashDrive. I would also like you to identify additional methods (functions) that would be appropriate for the class FlashDrive. Submit a .h file for FlashDrive with the new possible methods and members you have...

  • 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...

  • 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();...

  • 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)...

  • C++ Assignment Project 1 - NodeList Building upon the the ListNode/List code I would like you...

    C++ Assignment Project 1 - NodeList Building upon the the ListNode/List code I would like you to extend the interface of a list to have these member functions as well. struct ListNode { int element; ListNode *next; } Write a function to concatenate two linked lists. Given lists l1 = (2, 3, 1)and l2 = (4, 5), after return from l1.concatenate(l2)the list l1should be changed to be l1 = (2, 3, 1, 4, 5). Your function should not change l2and...

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