The following revised version of the
analyze_train
program replaces if-else
statements with a
switch
statement, includes error handling, and exploits enumeration
constants:
#include#include // Railroad car 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}; 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; default: cerr << "Car code " << type_code << " is unknown!" << endl; exit (0); } // Display classes using display_short_name virtual function: for (n = 0; n < car_count; ++n) { train[n] -> display_short_name ( ); cout << endl; } } --- Data --- 0 1 1 2 3 --- Result --- eng box box tnk cab