Arrays as Class Member Variables
-
A class can have arrays as member variables.
-
It is illustrated here in a class called TempertureList, which has an array or a list of temperatures called list as a member variable.
The array will typically be only partially filled and so a second member variable called size is used to specify the actual number of indexed variables of the array that are being used to store values.
-
//This is the INTERFACE for the class TemperatureList.
//Values of this type are lists of Fahrenheit temperatures.
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
const int MAX_LIST_SIZE = 50;
class TemperatureList
{
private:
double list[MAX_LIST_SIZE]; //of temperatures in Fahrenheit
int size; //number of array positions filled
public:
TemperatureList( );
//Initializes the object to an empty list.
void add_temperature(double temperature);
//Precondition: The list is not full.
//Postcondition: The temperature has been added to the list.
bool full( ) const;
//Returns true if the list is full. false otherwise.
void display_temperature( ) const;
//Temperatures are displayed on the screen one per line.
};
//This is the IMPLEMENTATION of the class TemperatureList.
TemperatureList::TemperatureList( )
{
size = 0;
}
//Uses iostream and cstdlib:
void TemperatureList::add_temperature(double temperature) {
if ( full( ) )
{
cout << "Error: adding to a full list.\n";
exit(1);
}
else
{
list[size] = temperature;
size = size + 1;
}
}
bool TemperatureList::full( ) const {
return (size == MAX_LIST_SIZE);
}
//Uses iostream:
void TemperatureList::display_temperature( ) const {
cout.setf(ios::fixed | ios::showpoint);
cout.precision(2);
cout << "This is the list of temperature in Fahrenheit:\n";
for (int i = 0; i < size; i++)
cout << setw(7) << list[i] << " F\n";
}
int main ( )
{
TemperatureList daily_high;
daily_high.add_temperature(59);
daily_high.add_temperature(63);
daily_high.add_temperature(64);
daily_high.display_temperature( );
return 0;
}