Professional Documents
Culture Documents
Solutions Manual
Visit to download the full and correct content document:
https://testbankdeal.com/download/absolute-c-6th-edition-savitch-solutions-manual/
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Chapter 6
Structures and Classes
Key Terms
structure
struct
structure tag
member name
where to place a structure definition
structure value
member value
member variable
reusing member names
structure variables in assignment statements
structure arguments
functions can return structures
class
object
member function
calling member functions
defining member functions
scope resolution operator
type qualifier
member variables in function definitions
data types and abstract types
encapsulation
private:
private member variable
public:
public member variable
accessor function
mutator function
interface
API
implementation
Brief Outline
6.1 Structures
Structure Types
Structures as Function Arguments
Initializing Structures
6.2 Classes
Defining Classes and Member Functions
Encapsulation
Public and Private Members
2. Key Points
Structures and Structure Types. Historical note: The name struct in C++ is provided
primarily for backward compatibility with ANSI C. Suppose we declare a struct, as in:
struct B
{
int x;
int y;
};
The text points out that the identifier B is called the structure tag. The structure tag B carries full
type information. The tag B can be used as you would use any built-in type. The identifiers x and
y declared in the definition of struct B are called member names. The members are variables are
associated with any variable of struct type. You can declare a variable of type B by writing1
B u;
You can access member variables (as l-values) by writing
u.x = 1;
u.y = 2;
or (as r-values)
int p, q;
p = u.x;
q = u.y;
We said in the previous paragraph that the tag B can be used as you would use any built-in type.
You can pass a struct to a function as a parameter, use a struct as a function return type, and
declare arrays of variables of type struct.
1
Contrast this with the C usage, struct B u;, where the keyword struct must be used in the definition of a
structure variable. This use is permitted in C++ for backward compatibility with C.
Our author points out that two identifiers that are declared to be of the same structure type may be
assigned, with member-wise assignment occurring.2 The critical issue here is that for assignment
compatibility the two structure variables must be declared with the same structure tag. In the
example that follows, the types are indistinguishable from the member structure within the struct.
However, C++ uses name equivalence for types, so the compiler looks at the tags in the
declarations rather than the structure to determine whether one struct variable may be assigned to
another. Example:
struct A
{
int x;
int y;
};
struct B
{
int x;
int y;
};
A u;
B v;
u = v; //type error: u and v are of different types
The error message from g++ 2.9.5 is:
// no match for 'A& = B&'
// candidates are: struct A& A::operator=(const A&)
Structures as Function Arguments. Since a structure tag is a type, the tag can be used as any other
type would be used. You can have arrays of structure objects, or function parameters that are call-by-value
or call-by-reference, and you can use a structure a type for the return type of a function.
Defining Classes and Member Functions. These remarks elaborate the ideas in the text on
class and the scope resolution operator, ::. A class definition (and a struct definition as well),
with the {}; define a scope within which variables and functions are defined. They are not
accessible outside without qualification by the object name and a dot operator . Member
functions are defined within a particular class, to be used by any object declared to be of that
class, again, only with qualification by being preceded by the object name and the dot operator.
To define a function whose prototype is given in a class we have to specify the scope of that
class within which the function is being defined. This is done with the class tag and scope
resolution operator.
To say:
returnTypeName class_tag::funcMemberName(argumentList)
{
//memberFunctionBody...
}
is to say "Within the scope of the class class_tag, define the function named funcMemberName
that has return type returnTypeName."
2
Member-wise assignment is the default for classes and structs. A former student of mine, John Gibson coined the
phrase, “Member UNWISE copy”. We will see that for classes with pointer members, member (un)wise copy is
almost never what you want.
The data members belong to a particular object, and function members must be called on behalf
of that particular object. The object must be specified. The object is specified by using the dot
operator used after the object name, before the member name or function call. Sometimes we
may speak of the calling object.
Abstract Data Types. The notion of Abstract Data Type (ADT) has two players: the author of
the ADT and the client of the ADT. The client knows only what the ADT will do, not how the
ADT carries out its tasks. The author of the ADT knows only what the ADT will do for the
client, but nothing about the context within which the ADT is used by the client. Information
hiding is a two way hiding. The separation of implementation (known only to the class author)
and the interface (the contract between ADT author and client) is vital. The other side of the
coin, namely the concealment from the ADT author of the context within which the ADT will be
used, is equally vital. This prevents either author from writing code that would depend on the
internals written by the other programmer.
Public and Private Members. The data members of a class are part of the implementation, not
part of the interface. The function members intended for use by the client are the interface. There
may be helping functions for the implementation that would be inappropriate for the client to
use, and so are not part of the interface. Normally the interface is made available to the client and
the implementation is hidden.
A struct, by default, allows access to its members by any function. A class, by default, allows
access to its members only to those functions declared within the class. This default access in a
struct is called public, and the default access in a class is called private.
The keywords private and public help manage hiding the implementation and making the
interface available to the client. These keywords are used to modify the default access to
members of a class or struct. The keyword private is used to hide members. The effect of the
keyword private: extends from the keyword private: to the next instance of the keyword public:.
The effect of the keyword public: extends from the keyword public: up to the next instance of the
keyword private:.
Accessor and Mutator Functions. It is the class author who writes the accessor and mutator
functions, so it is she who controls the access to the class data. If the data members were public,
any function has access in any way the client wishes. Data integrity will be compromised.
Structures versus Classes. This is the text’s “truth in advertising” section. Since this document
is for the instructor, little distinction between structs and classes is made here.
3. Tips
Hierarchical Structures. It is worth pointing out that the name spaces for hierarchical (or
nested) structures are separate. The same names can be used in the containing struct as are used
in the structure member. The same names can be used in two structures members at the same
level.
Example: Name space and hierarchical structure initialization
// file: ch6test2.cc
// purpose: test namespace in hierarchical structures
#include <iostream>
using namespace std;
struct A
{
int a;
int b;
};
struct B
{
A c;
int a;
int b;
};
int main()
{
A u = {1,2};
B v = {{3,4},4,5};
cout << "u.a = " << u.a << " u.b = " << u.b << endl;
cout << "v.c.a = " << v.c.a << " v.c.b = " << v.c.b
<< " v.a = " << v.a << " v.b = " << v.b << endl;
return 0;
}
This code compiles and runs as expected. The output is:
u.a = 1 u.b = 2
v.c.a = 3 v.c.b = 4 v.a = 4 v.b = 5
This is, of course, a "horrible example", designed to show a worst case. One would almost never
use the same identifiers in two structures while using a struct object as a member of another as
we do here. However, this does serve to illustrate the idea that the name spaces for two structures
are separate. (This is also true for classes as well.) In short, duplicating a member name where
needed won't break a program.
Initializing Structures. The previous example also illustrates that structure variables can be
assigned initial values using the curly brace notation.
Separate Interface and Implementation. The interface provides the API and helps abstract the
implementation details from a user of the class. This allows a programmer to change the
implementation without having to change other parts of the program.
A Test for Encapsulation. If you can change the implementation of a class without requiring a
change to the client code, you have the implementation adequately encapsulated.
Thinking Objects. When programming with classes, data rather than algorithms takes center
stage. The difference is in the point of view compared to students that have never programmed
with objects before.
4. Pitfalls
Omitting the semicolon at the end of a struct or class definition. The text points out that a
structure definition is required to have a semicolon following the closing curly brace. The reason
is that it is possible to define a variable of the struct type by putting the identifier between the
closed curly brace, }, and the semicolon.
struct A
{
int a;
int b;
} c;
The variable c is of struct type A. With some compilers, this pitfall generates particularly
uninformative error messages. It will be quite helpful for the student to write several examples in
which the closing semicolon in a structure definition is deliberately omitted.
//ch6Prg1.cpp
#include <iostream>
using namespace std;
//Grading Program
//Policies:
//
// Two quizzes, 10 points each
// midterm and final exam, 100 points each
// Of grade, final counts 50%, midterm 25%, quizes25%
//
// Letter Grade is assigned:
// 90 or more A
// 80 or more B
// 70 or more C
// 60 or more D
// less than 60, F
//
// Read a student's scores,
// output record: scores + numeric average + assigned letter grade
//
// Use a struct to contain student record.
struct StudentRecord
{
int studentNumber;
double quiz1;
double quiz2;
double midterm;
double final;
double average;
char grade;
};
int main()
{
StudentRecord student[CLASS_SIZE];
// Enclosing block fixes VC++ "for" loop control defined outside loop
{ for(int i = 0; i < CLASS_SIZE; i++)
{
computeGrade(student[i]);
output(student[i]);
cout << endl;
}
}
return 0;
}
cout << student.quiz1 << " " << student.quiz2 << endl;
cout << "enter the midterm and final exam grades."
<< "These are 100 point tests\n";
cin >> student.midterm >> student.final;
cout << student.midterm << " " << student.final
<< endl << endl;
}
Output:
2. CounterType
An object of CounterType is used to count things, so it records a count that is a nonnegative
integer number. It has mutators to increment by 1 and decrement by 1, but no member allows the
counter value to go negative.
There is an accessor that returns the count value, and a display function that displays the count
value on the screen.
Apropos of confusing error messages, this one is worth comment. In compiling the code for this
problem, the following warning message was generated from VC++6.0 on the last line of the
following code fragment:
warning: integral size mismatch in argument; conversion supplied
cout << "starting at counter value "
<< localCounter.currentCount
<< "and decrementing "
<< MAX << " times only decrements to zero.\n\n";
If the error message had been on the offending line, it would have been trivial to see the missing
parentheses on the second line of this code fragment. Warn the students that the error message
may be given several lines after the offending bit of code.
//Ch6prg2.cpp
//CounterType
//
// The class keeps a non-negative integer value.
// It has 2 mutators one increments by 1 and
// the other decrements by 1.
// No member function is allowed to drive the value of the counter
// to become negative. (How to do this is not specified.)
// It has an accessor that returns the count value,
// and a display member that write the current count value
// to the screen.
#include <iostream>
using namespace std;
class CounterType
{
public:
void InitializeCounter();
void increment();
void decrement();
int currentCount();
void display();
private:
int count;
};
int main()
{
CounterType localCounter;
localCounter.InitializeCounter();
{
for(int i = 1; i < MAX; i++)
if(i%3 == 0) // true when i is divisible by 3
localCounter.increment();
}
{
for(int i = 1; i < MAX; i++)
{
localCounter.display();
cout << " ";
localCounter.decrement();
}
}
cout << endl << endl;
return 0;
void CounterType::InitializeCounter()
{
count = 0;
}
void CounterType::increment()
{
count++;
}
void CounterType::decrement()
{
if(count > 0) count--;
}
void CounterType::display()
{
cout << count;
}
int CounterType::currentCount()
{
return count;
}
6 5 4 3 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0
3. A Point class
A point in the plane requires two coordinates. We could choose from many coordinate systems.
The two that are most familiar are rectangular and polar. We choose rectangular coordinates (two
double values representing distances from the point in question to perpendicular coordinates).
Conversion the internal representation of this class from rectangular to polar coordinates
should be an excellent problem for students who are reasonably prepared.
These members should be implemented:
a) a member function, set, to set the private data after creation
b) a member function to move the point a vertical distance and a horizontal distance
specified by the first and second arguments.
c) a member function that rotates the point 90 degrees clockwise about the origin.
d) two const inspector functions to retrieve the current coordinates of the point.
Document the member functions.
Test with several points exercise member functions.
//Ch6prg3.cpp
#include <iostream>
using namespace std;
// Point
// The members should implement
// a)a member function, set, to set the private data after creation
// b)a member function to move the point a vertical distance and a
// horizontal distance specified by the first and second arguments.
// c)a member function that rotates the point 90 degrees clockwise
// about the origin.
// d)two const inspector functions to retrieve the current coordinates
// of the point.
// Document the member functions.
// Test with several points exercise member functions.
class Point
{
public:
//set: set x to first, y to second
void set(int first, int second);
double Point::first()
{
return x;
}
double Point::second()
{
return y;
}
void Point::rotate()
{
double tmp = x;
x = -y;
y = tmp;
}
int main()
{
Point A, B, C;
A.set(1,2);
cout << A.first() << ", " << A.second() << endl;
A.rotate();
cout << A.first() << ", " << A.second() << endl;
A.rotate();
cout << A.first() << ", " << A.second() << endl;
A.rotate();
cout << A.first() << ", " << A.second() << endl;
A.rotate();
cout << A.first() << ", " << A.second() << endl;
A.rotate();
cout << A.first() << ", " << A.second() << endl;
B.set(2,3);
cout << B.first() << ", " << B.second() << endl;
B.move(1,1);
cout << B.first() << ", " << B.second() << endl;
C.set(5, -4);
cout << C.first() << ", " << C.second() << endl;
cout << "Move C by -5 horizontally and 4 vertically. " << endl;
C.move(-5, 4);
cout << C.first() << ", " << C.second() << endl;
return 0;
}
In this execution of the program: We start with (1,2). This point is rotated 90 degrees, four times,
getting back to the original point. The point (3,4) is set and moved by (1,1), that is, one up, one
right). A second point, (5,-4) is set and moved by (-5,4) one left, on down. Then we move it back
to the origin, (0,0). The output from this run is:
1, 2
-2, 1
-1, -2
2, -1
1, 2
-2, 1
2, 3
3, 4
5, -4
Move C by -5 horizontally and 4 vertically.
0, 0
1) Implement a class definition that models of the behavior of the gas pump.
2) Write implementations of the member functions.
3) Decide whether there are other data the pump must keep track of that the user should not
have access to.
Parts a) b) c) d) are straightforward to implement. Part e), the pumping operation is a little tricky.
Once I realized that the valve on the nozzle must be held to continue to dispense gas, I decided to
model that behavior by repeatedly pressing <CR> is an easy step. Tweaking the appearance and
behavior detail is all that was left. The tweaking was not trivial.
There are notes in the GasPump class definition that are addressed to the instructor. These
concern members that should be declared static or should have been members of a manager class
that is a friend of this class. The student is not likely to understand these notes. I suggest that you
delete these remarks if you give this solution to the student.
#include <iostream>
using namespace std;
class GasPump
{
public:
void initialize(); // set charges, amount dispensed, and
//gasInMainTank to 0.
void reset(); // set charges and amount dispensed to 0;
void displayCostPerGallon();
//If there is only one grade, of gasoline, this should be a static
//member of GasPump, since it would then apply to all instances of
//GasPump. If there are several grades, then this and costPerGallon
//should be ordinary members.
void displayGasNCharges();
// Dispense member continually updates display of new amount and
// new charges
void dispense();
void stop(); // If called, stops dispensing operation.
// My implementation never used this.
private:
double gasDispensed;
double charge;
public:
//Perhaps these functions should be static members of this class.
//See the earlier comment about this.
void setPricePerGallon(double newPrice);
void buyFromJobber(double quantity);
void displayAmountInMainTank();
private:
//These variables should be static members, since
//they are associated with all class instances.
double gasInMainTank;
double costPerGallon;
};
void GasPump::displayAmountInMainTank()
{
cout << gasInMainTank;
}
void GasPump::initialize()
{
gasDispensed = 0;
charge = 0;
gasInMainTank = 0;
}
void GasPump::reset()
{
gasDispensed = 0;
charge = 0;
}
void GasPump::displayCostPerGallon()
{
cout << costPerGallon;
}
void GasPump::displayGasNCharges()
{
cout << "gallons: " << gasDispensed
<< " $" << charge << endl;
}
void GasPump::dispense()
{
char quit;
while(gasInMainTank > 0)
{
quit = cin.get();
if (quit == 'q' || quit == 'Q')
break;
int main()
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
GasPump pump;
char ans;
pump.initialize();
pump.setPricePerGallon(1.50);
pump.buyFromJobber(25);
cout << "Amount of gasoline in main tank is: ";
pump.displayAmountInMainTank();
cout << endl;
pump.displayGasNCharges();
system("cls"); // Windows
//system("clear"); // Unix/Linux
return 0;
}
5. Fraction
Define a class for a type called Fraction. This class is used to represent a ratio of two integers.
Include mutator functions that allow the user to set the numerator and the denominator. Also
include a member function that returns the value of numerator / denominator as a double. Include
an additional member function that outputs the value of the fraction reduced to lowest terms, e.g.
instead of outputting 20/60 the method should output 1/3. This will require finding the greatest
common divisor for the numerator and denominator, and then dividing both by that number.
Embed your class in a test program.
//fraction.cpp
//This program defines a class for fractions, which stores a numerator
// and denominator. A member functions allows for retrieval of the
// fraction as a double and another outputs the value in lowest
// terms.
#include <iostream>
#include <cstdlib>
class Fraction
{
public:
double getDouble();
void outputReducedFraction();
void setNumerator(int n);
void setDenominator(int d);
private:
int numerator;
int denominator;
int gcd(); // Finds greatest common divisor of numerator
// and denominator
};
// --------------------------------
// ----- ENTER YOUR CODE HERE -----
// --------------------------------
// ======================
// Fraction::getDouble
// Returns the fraction's value as a double
// ======================
double Fraction::getDouble()
{
return (static_cast<double>(numerator) / denominator);
}
// ======================
// Fraction::outputReducedFraction
// Reduces the fraction and outputs it to the console.
// ======================
void Fraction::outputReducedFraction()
{
int g;
g = gcd();
cout << numerator / g << " / " << denominator / g << endl;
return;
}
// ======================
// Fraction::setNumerator
// Mutator to change the numerator
// ======================
void Fraction::setNumerator(int n)
{
numerator = n;
}
// ======================
// Fraction::setDenominator
// Mutator to change the denominator
// ======================
void Fraction::setDenominator(int d)
{
denominator = d;
}
// ======================
// Fraction::gcd
// Finds greatest common divisor of numerator and denominator
// by brute force (start at larger of two, work way down to 1)
// ======================
int Fraction::gcd()
{
int g; // candidate for gcd, start at the smaller of the
// numerator and denominator
// --------------------------------
// --------- END USER CODE --------
// --------------------------------
// ======================
// main function
// ======================
int main()
{
// Some test fractions
Fraction f1, f2;
f1.setNumerator(4);
f1.setDenominator(2);
cout << f1.getDouble() << endl;
f1.outputReducedFraction();
6. Odometer
Define a class called Odometer that will be used to track fuel and mileage for an automotive
vehicle. The class should have member variables to track the miles driven and the fuel efficiency
of the vehicle in miles per gallon. Include a mutator function to reset the odometer to zero miles,
a mutator function to set the fuel efficiency, a mutator function that accepts miles driven for a trip
and adds it to the odometer’s total, and an accessor method that returns the number of gallons of
gasoline that the vehicle has consumed since the odometer was last reset.
Use your class with a test program that creates several trips with different fuel efficiencies. You
should decide which variables should be public, if any.
//odometer.cpp
//This program defines an Odometer class to track fuel and mileage.
// It stores the miles driven and fuel efficient and includes
// a function to calculate the number of gallons of gasoline consumed.
#include <iostream>
#include <cstdlib>
class Odometer
{
public:
void setFuelEfficiency(double newEfficiency);
void reset();
void logMiles(int additionalMiles);
double gasConsumed();
private:
int miles;
double fuel_efficiency;
};
// --------------------------------
// ----- ENTER YOUR CODE HERE -----
// --------------------------------
// ======================
// Odometer::setFuelEfficiency
// Sets the fuel efficiency in miles per gallon.
// ======================
// ======================
// Odometer::reset
// Resets the odometer reading
// ======================
void Odometer::reset()
{
miles = 0;
}
// ======================
// Odometer::addMiles
// Log additional miles to the odometer.
// ======================
void Odometer::logMiles(int additionalMiles)
{
miles += additionalMiles;
}
// ======================
// Odometer::gasConsumed
// Calculates the gallons of gas consumed on the trip.
// ======================
double Odometer::gasConsumed()
{
return (miles / fuel_efficiency);
}
// --------------------------------
// --------- END USER CODE --------
// --------------------------------
// ======================
// main function
// ======================
int main()
{
// Two test trips
Odometer trip1, trip2;
trip1.reset();
trip1.setFuelEfficiency(45);
trip1.logMiles(100);
cout << "For your fuel-efficient small car:" << endl;
cout << "After 100 miles, " << trip1.gasConsumed() <<
" gallons used." << endl;
trip1.logMiles(50);
7. Pizza
Define a class called Pizza that has member variables to track the type of pizza (either deep
dish, hand tossed, or pan) along with the size (either small, medium, or large) and the number of
pepperoni or cheese toppings. You can use constants to represent the type and size. Include
mutator and accessor functions for your class. Create a void function, outputDescription( ),
that outputs a textual description of the pizza object. Also include a function, computePrice( ),
that computes the cost of the pizza and returns it as a double according to the rules:
Write a suitable test program that creates and outputs a description and price of various pizza
objects.
Notes: You may wish to point out that this could be better organized using inheritance and
classes for each type of pizza.
// pizza.h
//
// Interface file for the Pizza class.
class Pizza
{
public:
Pizza();
~Pizza() {};
int getPepperoniToppings();
void setPepperoniToppings(int numPepperoni);
int getCheeseToppings();
void setCheeseToppings(int numCheese);
int getSize();
void setSize(int newSize);
int getType();
void setType(int newType);
void outputDescription();
double computePrice();
private:
int size, type, pepperoniToppings, cheeseToppings;
};
// pizza.cpp
//
// This program implements the Pizza class and creates several
// pizza objects to test it out.
#include <iostream>
#include "pizza.h"
//========================
// Pizza
// The constructor sets the default pizza
// to a small, deep dish, with only cheese.
//========================
Pizza::Pizza()
{
size = SMALL;
type = DEEPDISH;
pepperoniToppings = 0;
cheeseToppings = 1;
}
//==================================
// Accessors and Mutators Follow
//==================================
// --------------------------------
// ----- ENTER YOUR CODE HERE -----
// --------------------------------
int Pizza::getPepperoniToppings()
{
return pepperoniToppings;
}
int Pizza::getCheeseToppings()
{
return cheeseToppings;
int Pizza::getSize()
{
return size;
}
int Pizza::getType()
{
return size;
}
//==================================
// outputDescription
// Prints a textual description of the contents of the pizza.
//==================================
void Pizza::outputDescription()
{
cout << "This pizza is: ";
switch (size)
{
case SMALL: cout << "Small, ";
break;
case MEDIUM: cout << "Medium, ";
break;
case LARGE: cout << "Large, ";
break;
default: cout << "Unknown size, ";
}
switch (type)
{
case DEEPDISH: cout << "Deep dish, ";
break;
case HANDTOSSED: cout << "Hand tossed, ";
break;
case PAN: cout << "Pan, ";
break;
default: cout << "Uknown type, ";
}
cout << "with " << pepperoniToppings << " pepperoni toppings " <<
"and " << cheeseToppings << " cheese toppings." << endl;
}
//==================================
// computePrice
// Returns:
// Price of a pizza using the formula:
// Small = $10 + $2 per topping
// Medium = $14 + $2 per topping
// Large = $17 + $2 per topping
//==================================
double Pizza::computePrice()
{
double price = 0;
switch (size)
{
case SMALL: price = 10; break;
case MEDIUM: price = 14; break;
case LARGE: price = 17; break;
default: cout << "Error, invalid size." << endl;
return -1;
}
price += (pepperoniToppings + cheeseToppings) * 2;
return price;
}
// --------------------------------
// --------- END USER CODE --------
// --------------------------------
// ======================
// main function
// ======================
int main()
{
// Variable declarations
Pizza cheesy;
Pizza pepperoni;
cheesy.setCheeseToppings(3);
cheesy.setType(HANDTOSSED);
cheesy.outputDescription();
cout << "Price of cheesy: " << cheesy.computePrice() << endl;
pepperoni.setSize(LARGE);
pepperoni.setPepperoniToppings(2);
pepperoni.setType(PAN);
pepperoni.outputDescription();
cout << "Price of pepperoni : " << pepperoni.computePrice() << endl;
cout << endl;
}
8. Money
Define a class named Money that stores a monetary amount. The class should have two private
integer variables, one to store the number of dollars and another to store the number of cents.
Add accessor and mutator functions to read and set both member variables. Add another
function that returns the monetary amount as a double. Write a program that tests all of your
functions with at least two different Money objects.
#include <iostream>
using namespace std;
class Money
{
public:
int getDollars();
int getCents();
void setDollars(int d);
void setCents(int c);
double getAmount();
private:
int dollars;
int cents;
};
int Money::getDollars()
{
return dollars;
}
int Money::getCents()
{
return cents;
}
void Money::setDollars(int d)
{
dollars = d;
}
void Money::setCents(int c)
{
cents = c;
}
double Money::getAmount()
{
return static_cast<double>(dollars) +
static_cast<double>(cents) / 100;
}
int main( )
{
Money m1, m2;
m1.setDollars(20);
m1.setCents(35);
m2.setDollars(0);
m2.setCents(98);
#include <iostream>
using namespace std;
class Money
{
public:
int getDollars();
int getCents();
void setDollars(int d);
void setCents(int c);
double getAmount();
private:
//int dollars, cents; // In OLD version
double amount;
};
int Money::getDollars()
{
// return dollars
return static_cast<int>(amount);
}
int Money::getCents()
{
//return cents;
int val = static_cast<int>(amount * 100);
if (val > 0)
return val % 100;
void Money::setDollars(int d)
{
int pennies = getCents(); // Current cents
amount = static_cast<double>(d) + (pennies / 100.0);
//dollars = d;
}
void Money::setCents(int c)
{
amount = static_cast<double>(getDollars()) +
(c / 100.0);
//cents = c;
}
double Money::getAmount()
{
//return static_cast<double>(dollars) +
// static_cast<double>(cents) / 100;
return amount;
}
#include <iostream>
using namespace std;
class Temperature
{
public:
void setTempKelvin(double temp);
void setTempFahrenheit(double temp);
void setTempCelsius(double temp);
double getTempKelvin();
double getTempFahrenheit();
double getTempCelsius();
private:
double kelvin; // Internally store temp in kelvin
};
double Temperature::getTempKelvin()
{
return kelvin;
}
double Temperature::getTempCelsius()
{
return kelvin - 273.15;
}
double Temperature::getTempFahrenheit()
{
int main( )
{
Temperature temp;
temp.setTempFahrenheit(32);
cout << "In Celsius: " << temp.getTempCelsius() << endl;
cout << "In Fahrenheit: " << temp.getTempFahrenheit() << endl;
cout << "In Kelvin: " << temp.getTempKelvin() << endl;
cout << endl;
temp.setTempCelsius(100);
cout << "In Celsius: " << temp.getTempCelsius() << endl;
cout << "In Fahrenheit: " << temp.getTempFahrenheit() << endl;
cout << "In Kelvin: " << temp.getTempKelvin() << endl;
cout << endl;
temp.setTempKelvin(0);
cout << "In Celsius: " << temp.getTempCelsius() << endl;
cout << "In Fahrenheit: " << temp.getTempFahrenheit() << endl;
cout << "In Kelvin: " << temp.getTempKelvin() << endl;
cout << endl;
Do Programming Project 5.18 except use only one array as a parameter instead of two arrays.
The single array should be of type Player where Player is a class that you create. The
Player class should have a member variable of type string to store the player's name and a
member variable of type int to score the player's score. Encapsulate these variables
appropriately. When your function returns the array entry at index 0 should be set to the name
and score of the player with the top score, the entry at index 1 should be set to the name and
score of the player with the second best score, etc.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Player
{
public:
void setName(string newname);
void setScore(int newscore);
string getName();
int getScore();
private:
string name;
int score;
};
int main( )
{
Player players[100];
getHighScores(players);
return 0;
}
string curname;
int curscore;
fstream inputStream;
inputStream.open("scores.txt");
while (inputStream >> curname)
{
inputStream >> curscore;
players[numScores].setScore(curscore);
players[numScores].setName(curname);
numScores++;
}
sort(players, numScores);
}
return indexOfMax;
}
Your Community Supported Agriculture (CSA) farm delivers a box of fresh fruits and
vegetables to your house once a week. For this Programming Project, define the class
BoxOfProduce that contains exactly three bundles of fruits or vegetables. You can represent
the fruits or vegetables as an array of type string. Add accessor and mutator functions to get
or set the fruits or vegetables stored in the array. Also write an output function that displays
the complete contents of the box on the console.
Next write a main function that creates a BoxOfProduce with three items randomly selected
from this list:
Broccoli
Tomato
Kiwi
Kale
Tomatillo
This list should be stored in a text file that is read in by your program. For now you can assume
that the list contains exactly five types of fruits or vegetables.
Don't worry if your program randomly selects duplicate produce for the three items. Next, the
main function should display the contents of the box and allow the user to substitute any one of
the five possible fruits or vegetables for any of the fruits or vegetables selected for the box.
After the user is done with substitutions output the final contents of the box to be delivered.
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
class BoxOfProduce
{
private:
int numBundles;
string bundle[MAX_BUNDLES];
public:
void initialize();
void addBundle(string b);
string getBundle(int index);
void setBundle(string b, int index);
string boxContents();
};
{
numBundles = 0;
}
void BoxOfProduce::addBundle(string b)
{
if (numBundles < MAX_BUNDLES)
{
bundle[numBundles] = b;
numBundles++;
}
}
int main()
{
// Create a Box
BoxOfProduce box;
box.initialize();
int lineRead = 0;
ifstream inputStream;
inputStream.open("produce.txt");
string food;
while (inputStream >> food)
{
if (lineRead == num1)
box.addBundle(food);
if (lineRead == num2)
box.addBundle(food);
if (lineRead == num3)
box.addBundle(food);
lineRead++;
}
inputStream.close();
Do Programming Project 5.19 except use a class named Player to store a player’s name and
score. Then, use an array of the Player class to store the 10 players.
#include <iostream>
#include <string>
using namespace std;
class Player
{
private:
string name;
int score;
public:
void setName(string newName);
void setScore(int newScore);
string getName();
int getScore();
};
// Prototypes
void addPlayer(int &numPlayers, Player players[]);
void printPlayers(int numPlayers, Player players[]);
void searchPlayers(int numPlayers, Player players[]);
void removePlayer(int &numPlayers, Player players[]);
cout << players[i].getName() << " " << players[i].getScore() << endl;
}
int main()
{
char option;
Player players[10];
int numPlayers=0;
// Initialize arrays
for (int i =0; i < 10; i++)
{
players[i].setScore(0);
players[i].setName("");
do
{
cout << "Enter an option." << endl;
cout << "a. Add new player and score." << endl;
cout << "b. Print all players and scores." << endl;
cout << "c. Search for a player's score." << endl;
cout << "d. Remove a player." << endl;
cout << "e. Quit." << endl;
return 0;
}