Question

In: Computer Science

How do I add an output operator to a class in C++? The specific part of...

How do I add an output operator to a class in C++?

The specific part of the task said to:

Define a ​class t​o hold accounts. Use the ​same​ stream variable! Write getters to access the fields in the accounts when printing. Add an output operator for your class. First, Repeat the print loop using this output operator.Now​ make the output operator a friend, by adding a friend​prototype​ to your account class definition. Add a line in the output operator that prints the fields “directly”, i.e. without using the getters. The vector push_back method will be passed as temporary object defined as the argument to push_back. Repeat the filling of the vector using ​emplace_back ​and again display the contents.

Under my "class AccountClass":

I was supposed to add an "output operator". Based on the instructions above, how do you do this?

Code:

#include
#include
#include
#include
#include
#include

using namespace std;

struct Account
{
   string name;
   int accno;
};

class Transaction
{
private:
   bool isDeposit;
   int amount;
   //Balance need to be static to maintain the state across the transactions
   static int balance;
public:
   void deposit(int amt)
   {
       amount = amt;
       balance += amount;
       isDeposit = true;
   }
   void withdraw(int amt)
   {
       amount = amt;
       balance -= amount;
       isDeposit = false;
   }
};

class AccountClass
{
private:
   string name;
   int accno;
   vector vHistory;
public:
   AccountClass(string nm, int acno) :name(nm), accno(acno)
   {

   }
   string getName()
   {
       return name;
   }

   int getaccno()
   {
       return accno;
   }

   void addTransaction(Transaction t)
   {
       vHistory.push_back(t);
   }
};

void readandDisplayUsingStruct(string fileName= "accounts.txt")
{
   ifstream fin;

   fin.open(fileName);

   if (!fin.is_open())
       return;

   string line;

   vector vAccounts;

   //Read each line from the file
   while (getline(fin, line))
   {
       stringstream ss(line);
       string name;
       int no;
       //Split the line into name and id using string stream
       ss >> name;
       ss >> no;
       Account acc{ name,no };
       vAccounts.push_back(acc);
   }

   cout << "The Read Values are" << endl;

   for (Account acc : vAccounts)
   {
       cout << "Name : " << acc.name << "\n";
       cout << "No : " << acc.accno << "\n";
   }

   //Clear the vector
   vAccounts.clear();

   fin.close();

   //Again do the same operation using local variables without Braces Initialisation.
   fin.open(fileName);

   if (!fin.is_open())
       return;

   string line1;

   vector vAccounts2;

   //Read each line from the file
   while (getline(fin, line1))
   {
       stringstream ss(line1);
       string name;
       int no;
       //Split the line into name and id using string stream
       ss >> name;
       ss >> no;
       Account acc;
       //Explicit initialisation
       acc.name = name;
       acc.accno = no;
       vAccounts2.push_back(acc);
   }

   std::cout << "The Read Values are" << endl;

   for (Account acc : vAccounts)
   {
       std::cout << "Name : " << acc.name << "\n";
       std::cout << "No : " << acc.accno << "\n";
   }

   fin.close();

}

void readandDisplayUsingClass(string fileName)
{
   ifstream fin;

   fin.open(fileName);

   if (!fin.is_open())
       return;

   string line;

   vector vAccounts;

   //Read each line from the file
   while (getline(fin, line))
   {
       stringstream ss(line);
       string name;
       int no;
       //Split the line into name and id using string stream
       ss >> name;
       ss >> no;
       AccountClass acc(name, no);
       vAccounts.push_back(acc);
   }

   std::cout << "The Read Values are" << endl;

   for (AccountClass acc : vAccounts)
   {
       std::cout << "Name : " << acc.getName() << "\n";
       std::cout << "No : " << acc.getaccno() << "\n";
   }

   //Clear the vector
   vAccounts.clear();

   fin.close();

}

int main()
{
   ifstream fin;

   fin.open("transactions.txt");

   if (!fin.is_open())
       return 0;

   string line;

   vector vAccounts;

   //Read each line from the file
   while (getline(fin, line))
   {
       stringstream ss(line);
       string operation;
       if (operation == "Deposit" || operation == "Withdraw")
       {
           int accno;
           ss >> accno;
           auto itr = std::find_if(vAccounts.begin(), vAccounts.end(), [&](AccountClass anAccount)
               {
                   return anAccount.getaccno() == accno;
               });

           if (itr != vAccounts.end())
           {
               Transaction t;
               int amount;
               ss >> amount;

               if (operation == "Deposit")
               {
                   t.deposit(amount);
               }
               else
               {
                   t.withdraw(amount);
               }

               itr->addTransaction(t);
           }
       }
       else if (operation == "Account")
       {
           string accName;
           ss >> accName;
           auto itr = std::find_if(vAccounts.begin(), vAccounts.end(), [&](AccountClass anAccount)
               {
                   return anAccount.getName() == accName;
               });

           if (itr == vAccounts.end())
           {
               int accno;
               ss >> accno;
               AccountClass newAccount(accName, accno);
               vAccounts.push_back(newAccount);
           }

       }

   }
}


Here is more information based on the expert’s comments: (i am just pasting the whole question since you did not specify what info you need, all my code is already posted)

Step 1: Define a ​struct​ that can hold information about bank accounts. First: ■ Each instance will hold the name for the account and an account number. We have created an input file that has at least three accounts, called "accounts.txt":
"moe 6
larry 28
curly 42"
Read a file of account information, filling a vector of account objects. Define local variables corresponding to each data item. Loop through the file, reading into these variables. Clear the vector, reopen the file (call the open method), and​repeat the above, except using curly braced intializers to intialize the instance. Close the file and display all objects.

Step 2: Define a ​class t​o hold accounts. Redo the above steps from task 1 that you did with the struct version. Use the ​same​ stream variable! Write getters to access the fields in the accounts when printing. Add an output operator for your class. First, Repeat the print loop using this output operator.Now​ make the output operator a friend, by adding a friend​prototype​ to your account class definition. Add a line in the output operator that prints the fields “directly”, i.e. without using the getters. The vector push_back method will be passed as temporary object defined as the argument to push_back. Repeat the filling of the vector using ​emplace_back ​and again display the contents.

Step 3: Add ​transactions​ to your world. A transaction will be implemented as a class and have a field to indicate whether this is a deposit or a withdrawal and a field to say how much is being deposited or withdrawn. The account class will keep track of transactions applied to it. It will need a vector to store this history of transactions. It will also need a "balance" field to indicate how much is in the account. The account will have methods "deposit" and "withdrawal" which will be passed the amount and will add an appropriate transaction object to the history and modify the balance as needed. The output operator for the account will need to change so that it can display (you format it) the history, i.e. the transactions. When you finish, test this by reading in another file "transactions.txt" that has commands such as:
"Account moe 6
Deposit 6 10
Withdraw 6 100
Account larry 28
Withdraw 6 100
Deposit 6 10
Deposit 6 10
Withdraw 6 5
Account curly 42"

Solutions

Expert Solution

// Output operator has been added to class AccountClass (bolded)

#include <iostream>

#include <vector>

#include <fstream>

#include <algorithm>

#include <sstream>

using namespace std;

struct Account

{

   string name;

   int accno;

};

class Transaction

{

private:

   bool isDeposit;

   int amount;

   //Balance need to be static to maintain the state across the transactions

   static int balance;

public:

   void deposit(int amt)

   {

       amount = amt;

       balance += amount;

       isDeposit = true;

   }

   void withdraw(int amt)

   {

       amount = amt;

       balance -= amount;

       isDeposit = false;

   }

};

int Transaction::balance = 0; // initialize balance to be 0 at the start

class AccountClass

{

private:

   string name;

   int accno;

   vector<Transaction> vHistory;

public:

   AccountClass(string nm, int acno) :name(nm), accno(acno)

   {

   }

   string getName()

   {

       return name;

   }

   int getaccno()

   {

       return accno;

   }

   void addTransaction(Transaction t)

   {

       vHistory.push_back(t);

   }

   // output operator declaration

   friend ostream& operator<<(ostream &out, const AccountClass &account);

};

// output operator overloading to print the name and account no of the account

ostream& operator<<(ostream &out, const AccountClass &account)

{

       out << "Name : " << account.name << "\n";

       out << "No : " << account.accno << "\n";

       return out;

}

void readandDisplayUsingStruct(string fileName= "accounts.txt")

{

   ifstream fin;

   fin.open(fileName);

   if (!fin.is_open())

       return;

   string line;

   vector<Account> vAccounts;

   //Read each line from the file

   while (getline(fin, line))

   {

       stringstream ss(line);

       string name;

       int no;

       //Split the line into name and id using string stream

       ss >> name;

       ss >> no;

       Account acc{ name,no };

       vAccounts.push_back(acc);

   }

   cout << "The Read Values are" << endl;

   for (Account acc : vAccounts)

   {

       cout << "Name : " << acc.name << "\n";

       cout << "No : " << acc.accno << "\n";

   }

   //Clear the vector

   vAccounts.clear();

   fin.close();

   //Again do the same operation using local variables without Braces Initialisation.

   fin.open(fileName);

if (!fin.is_open())

       return;

   string line1;

   vector<Account> vAccounts2;

   //Read each line from the file

   while (getline(fin, line1))

   {

       stringstream ss(line1);

       string name;

       int no;

       //Split the line into name and id using string stream

       ss >> name;

       ss >> no;

       Account acc;

       //Explicit initialisation

       acc.name = name;

       acc.accno = no;

       vAccounts2.push_back(acc);

   }

   std::cout << "The Read Values are" << endl;

   for (Account acc : vAccounts)

   {

       std::cout << "Name : " << acc.name << "\n";

       std::cout << "No : " << acc.accno << "\n";

   }

   fin.close();

}

void readandDisplayUsingClass(string fileName)

{

   ifstream fin;

   fin.open(fileName);

   if (!fin.is_open())

       return;

   string line;

   vector<AccountClass> vAccounts;

   //Read each line from the file

   while (getline(fin, line))

   {

       stringstream ss(line);

       string name;

       int no;

       //Split the line into name and id using string stream

       ss >> name;

       ss >> no;

       AccountClass acc(name, no);

       vAccounts.push_back(acc);

   }

   std::cout << "The Read Values are" << endl;

   for (AccountClass acc : vAccounts)

   {

          std::cout<<acc; // the operator<< class is used to output the name and accno

          /*std::cout << "Name : " << acc.getName() << "\n";

       std::cout << "No : " << acc.getaccno() << "\n";*/

   }

   //Clear the vector

   vAccounts.clear();

   fin.close();

}

int main()

{

   ifstream fin;

   fin.open("transactions.txt");

   if (!fin.is_open())

       return 0;

   string line;

   vector<AccountClass> vAccounts;

   //Read each line from the file

   while (getline(fin, line))

   {

       stringstream ss(line);

       string operation;

       if (operation == "Deposit" || operation == "Withdraw")

       {

           int accno;

           ss >> accno;

           auto itr = std::find_if(vAccounts.begin(), vAccounts.end(), [&](AccountClass anAccount)

               {

                   return anAccount.getaccno() == accno;

               });

           if (itr != vAccounts.end())

           {

               Transaction t;

               int amount;

               ss >> amount;

               if (operation == "Deposit")

               {

                   t.deposit(amount);

               }

               else

               {

                   t.withdraw(amount);

               }

               itr->addTransaction(t);

           }

       }

       else if (operation == "Account")

       {

           string accName;

           ss >> accName;

           auto itr = std::find_if(vAccounts.begin(), vAccounts.end(), [&](AccountClass anAccount)

               {

                   return anAccount.getName() == accName;

               });

           if (itr == vAccounts.end())

           {

               int accno;

               ss >> accno;

               AccountClass newAccount(accName, accno);

               vAccounts.push_back(newAccount);

           }

       }

   }

   return 0;

}


Related Solutions

How do I add white space in the beginning of my printf statement in C? I...
How do I add white space in the beginning of my printf statement in C? I also need the white space to be dynamic by using an int value as reference for the amount of spaces. Thanks!
How do I add additional command line arguments in C++? I am working on a programming...
How do I add additional command line arguments in C++? I am working on a programming assignment that has the user input a file into the command line and then they have the option to also add a series of other arguments to the command line. I know how to accept the text file from the command line by using: int main(int argc, char *argv[]) { /.../ } Then filename(argv[1]) would be the text file that they put into the...
c++ using class... define operator overloading and give simple example how we can use operator overloading...
c++ using class... define operator overloading and give simple example how we can use operator overloading by writing simple program in which different operators are used to add, subtract, multiply and division.
C# Programming (Class Registration class) Add a Schedule property to the Person class. Add a new...
C# Programming (Class Registration class) Add a Schedule property to the Person class. Add a new behavior as well: add(Section s) this behavior will add a section to the Person’s schedule. The Person’s display() function will also need to be modified to display() the Person’s Schedule. Schedule class has Properties: An array of Sections and a Count. Constructors: only a default constructor is needed. Behaviors: add() and display(). This is my schedule class class Schedule     {         private int...
Define a problem with user input, user output, -> operator and destructors. C ++ please
Define a problem with user input, user output, -> operator and destructors. C ++ please
How do I fix the "error: bad operand types for binary operator '*' " in my...
How do I fix the "error: bad operand types for binary operator '*' " in my code? What I am trying to do: double TotalPrice = TicketPrice * NoOfTickets;       My code: import javax.swing.*; /*provides interfaces and classes for different events by AWT components*/ import java.awt.event.*; import javax.swing.JOptionPane; //TicketReservation.java class TicketReservation { public static void main(String args[]) { /*Declare JFrame for place controls.*/ JFrame f= new JFrame("Movie Ticket Reservation");                                   /*Declare JLabels*/ JLabel...
I have defined the class. Rectangle in Python. How do I define a class Canvas with...
I have defined the class. Rectangle in Python. How do I define a class Canvas with the following description: Class Canvas represents a collection of Rectangles. It has 8 methods. In addition, to the constructor (i.e. __init__ method) and two methods that override python's object methods (and make your class user friendly as suggested by the test cases), your class should contain 5 more methods: add_one_rectangle, count_same_color, total_perimeter, min_enclosing_rectangle, and common_point.
WRITE IN C++ Add to the Coord class Edit the provided code in C++ Write a...
WRITE IN C++ Add to the Coord class Edit the provided code in C++ Write a member function named      int distance2origin() that calculates the distance from the (x, y, z) point to the origin (0, 0, 0) the ‘prototype’ in the class definition will be      int distance2origin() outside the class definition             int Coord :: distance2origin() {                         // your code } _______________________________________________________________________________________________________ /************************************************** * * program name: Coord02 * Author: * date due: 10/19/20 * remarks:...
C++ please. Define a problem with user input, user output, Pointer, with const and sizeof operator.
C++ please. Define a problem with user input, user output, Pointer, with const and sizeof operator.
In class we discussed how to overload the + operator to enable objects of type Fraction to be added together using the + operator.
2.(a) Fraction Operators Objective:In class we discussed how to overload the + operator to enable objects of type Fraction to be added together using the + operator. Extend the Fraction class definition so that the -, * and / operators are supported. Write a main function that demonstrates usage of all of these operators.(b)More Custom Types Objective:Define a set of classes that represent a Schedule and Course in the context of a university student who has a schedule with a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT