Last week we finished creating the classes for GroceryList and GroceryItem, now we have to create an application. Once again our application will have a run function that is called from the main function. This application is more complex because it requires that the program ask the user to choose an operation, then the program will actually carry out the operation. This will require creating a menu.
Next the functions of the application should be listed. There should be one for each operation the user can do. In this case the functions are:
void MyApplication::run()
{
MyMenu menu;
ifstream in("grocery.dat");
if (!in)
throw "File of groceries not found";
groceries.read(in);
in.close();
int choice;
do {
choice = menu.makeChoice();
switch (choice) {
case 0: addItem(); break;
case 1: computeCost(); break;
case 2: printList(); break;
}
}while (choice != 3);
ofstream out("grocery.dat");
if(!out)
throw "File of groceries not found";
groceries.write(out);
out.close();
}
Most of the code is fairly clear except for the switch statement - see text for explanation.
Notice that the choice 3 is not a case of the switch, it is quit. When the user chooses quite
the loop terminates. For more details on this code click here.
If you have a container with more than one type of object such as the various types of Employee in last weeks problem, you must use an array of counted pointers to Employee.
typedef RcPointer < Employee > EmployeePtr; Array < EmployeePtr > EmployeeArray;When reading a file use the techniques we discussed at that time to read objects. This requires that you save the type of each object as an enumerated type when you write to the file, and retrieve this when you read. I recommend again that you save the number in the array before the array.
Our Easy Windows version of the grocery list program took a traditional terminal-oriented approach to implementing a menu. Today most programs have a user-friendly type of windows interface. We are going to rebuild our program with a simple windows interface. This will be the first step in creating a Windows application, so it will not have all of the bells and whistles of a typical Windows program.
For this application we will use the simplest type of window, a TWindow. TWindows provide a menu and a framework for calling on subwindows. In our program we will modify the menu to include our operations on the GroceryList, and use two built-in types of dialog windows for our I/O.
Our application already has a menu bar associated with it. We will add to this menu bar, but will not try to make a perfect menu bar at this time. First, go to class expert and select the TWindow Class. Then use the right button menu to select Edit Menu. Click here for a summary of menu construction.
At this time we make a brief detour to a simple application of menus and the TWindow class. One of the standard applications of object-oriented design is the simulation. Click here for the notes on this simulation.