Handout 6
Classes
1 class SaleItem
2 {
3 public:
4 double getprice();
5 void setprice(double);
6 void setName(string);
7 string getName();
8 double TotalItemsPrice(int);
9 private:
10 double
price;
11 string name;
12 };
a) In the class declaration above, what
is the name of the class?
b) Which lines have member access specifiers?
c) Which lines contain data members of
the class?
d) Which lines contain accessor functions?
e) Which lines contain mutator functions?
#include<iostream>
#include<fstream>
using namespace std;
class Tank
{
public:
void setCapacity(int);
int getGallons()
const;
void useGallons(int);
int getCapacity();
void fillTank();
private:
int capacity;
int gallons;
};
int main()
{
Tank myCar;
Tank myVan;
int miles;
myCar.setCapacity(20);
myVan.setCapacity(35);
cout
<< "My car has a capacity of "
<< myCar.getCapacity() << endl;
cout
<< "My van has a capacity of "
<< myVan.getCapacity() << endl;
myVan.fillTank();
myCar.fillTank();
cout
<< "My car has " << myCar.getGallons() << "
gallons gas" << endl;
cout
<< "My van has " << myVan.getGallons() << "
gallons gas" << endl;
myVan.useGallons(10);
myCar.useGallons(6);
cout
<< "My car has " << myCar.getGallons() << "
gallons gas" << endl;
cout
<< "My van has " << myVan.getGallons() << "
gallons gas" << endl;
return
0;
}
void Tank::setCapacity(int cap)
{
capacity = cap;
}
int Tank::getGallons()
const
{
return
gallons;
}
void Tank::useGallons(int g)
{
gallons -= g;
}
int Tank::getCapacity()
{
return capacity;
}
void Tank::fillTank()
{
gallons =
capacity;
}