Home Segments Index Top Previous Next

576: Mainline

Now that you have overloaded the output operator, enabling it to handle railroad_car objects, you can use dereferenced railroad-car pointers as output-operator operands, as in the following version of the analyze_train program:

#include   
const double pi = 3.14159; 
// Class definitions go here 
// Define railroad-car pointer array: 
railroad_car *train[100]; 
// Declare enumeration constants, needed in switch statement: 
enum {eng_code, box_code, tnk_code, cab_code}; 
// Overload <<: 
ostream& operator<< (ostream& output_stream, railroad_car& r) { 
  output_stream << "[" << r.short_name ( ) << "]"; 
  return output_stream;} 
main ( ) { 
  // Declare various integer variables: 
  int n, car_count, type_code; 
  // Read car-type number and create car class objects: 
  for (car_count = 0; cin >> type_code; ++car_count) 
    switch (type_code) { 
      case eng_code: train[car_count] = new engine;   break; 
      case box_code: train[car_count] = new box_car;  break; 
      case tnk_code: train[car_count] = new tank_car; break; 
      case cab_code: train[car_count] = new caboose;  break; 
    } 
  // Display icons: 
  cout << *train[0]; 
  for (n = 1; n < car_count; ++n) { 
    cout << "-" << *train[n]; 
    } 
  cout << endl; 
} 
--- Data ---
0 1 1 2 3 
--- Result --- 
[eng]-[box]-[box]-[tnk]-[cab] 

Thus, the overloaded output operator always displays the appropriate three-letter short name, surrounded by brackets. It also returns the same output stream that appeared as the left-side operand.