Introduction to classes cont.
This lesson contains approximately 45 minutes of video content.
Constructors and destructors
In-class member initializers
Public / private distinction
Interfaces
Private member functions
Non-member "helper" functions
Activity: Running total class implementation
Graded Playground Autograder
Activity Prompt:
Define the class RunningTotal
according to the following specification. Be sure to include the necessary header files. The solution constraints section give some hints on which headers will be needed.
Private data members
total_
typedint
history_
typedstd::vector<RunningTotalHistoryEntry>
Public member functions
Remember to declare the member functions that do not modify object state as const
.
RunningTotal()
, a default constructor that initializestotal_
with0
.CurrentTotal()
- Returns the value stored in
total_
- Therefore, the return type of
CurrentTotal()
isint
- Returns the value stored in
Add(int value)
- Increments the
RunningTotal
object'stotal_
data member withvalue
. - Pushes back to the
RunningTotal
object'shistory_
anRunningTotalHistoryEntry
whoseoperation
is+
andvalue
is that stored in this function'svalue
parameter.
- Increments the
Subtract(int value)
- Decrements the
RunningTotal
object'stotal_
data member withvalue
. - Pushes back to the
RunningTotal
object'shistory_
anRunningTotalHistoryEntry
whoseoperation
is-
andvalue
is that stored in this function'svalue
parameter.
- Decrements the
History()
- Returns an
std::string
representation of the contents of theRunningTotal
object'shistory_
according to the prescribed format that follows.- The string will always begin with
0
- For each element in
history_
, visited from the first element (that at index0
) to the last element (that at indexhistory_.size() - 1
).- Concatenate the visited
RunningTotalHistoryEntry
object'soperation
value to the string. - Concatenate the visited
RunningTotalHistoryEntry
object'svalue
to the string. To do this, you must convert the integervalue
to anstd::string
usingstd::to_string
.
- Concatenate the visited
- The string will always begin with
- Return the
std::string
you have constructed to the caller. - Example:
-
RunningTotal rt; rt.Add(10); rt.Subtract(1); rt.Add(5); rt.History(); // returns the following std::string: "0+10-1+5"
-
- Returns an
Graded Files
Only the following files are transferred to the autograder.
running-total.hpp
running-total.cc
#include "running-total.hpp"
int main() {
}
#ifndef RUNNING_TOTAL_HPP
#define RUNNING_TOTAL_HPP
#endif
#include "running-total.hpp"
#ifndef RUNNING_TOTAL_HISTORY_ENTRY_HPP
#define RUNNING_TOTAL_HISTORY_ENTRY_HPP
struct RunningTotalHistoryEntry {
char operation = '\0';
int value = 0;
};
#endif
Submit is not supported in this site.