8.9.3 实现CBox类(9)
使用CBox类,该问题很容易解决,解决方案由下面的main()函数给出。像以前一样,右击Solution Explorer窗格中的Source Files文件夹,从弹出的上下文菜单中选择适当的菜单项,给本项目添加一个新的C++(www.cppentry.com)源文件Ex8_12.cpp,然后输入下面显示的代码:
- // Ex8_12.cpp
- // A sample packaging problem
- #include <iostream>
- #include "Box.h"
- #include "BoxOperators.h"
- using std::cout;
- using std::endl;
- int main()
- {
- CBox candy(1.5, 1.0, 1.0); // Candy definition
- CBox candyBox(7.0, 4.5, 2.0); // Candy box definition
- CBox carton(30.0, 18.0, 18.0); // Carton definition
- // Calculate candies per candy box
- int numCandies = candyBox/candy;
- // Calculate candy boxes per carton
- int numCboxes = carton/candyBox;
- // Calculate wasted carton space
- double space = carton%candyBox;
- cout << endl << "There are " << numCandies << " candies per candy box" << endl
- << "For the standard boxes there are " << numCboxes
- << " candy boxes per carton " << endl << "with "
- << wasted << " cubic inches wasted.";
- cout << endl << endl << "CUSTOM CANDY BOX ANALYSIS (No Waste)";
- const int minCandiesPerBox = 30;
- // Try the whole range of custom candy boxes
- for(double length = 3.0 ; length <= 7.5 ; length += 0.5)
- {
- for(double width = 3.0 ; width <= 5.0 ; width += 0.5)
- {
- for(double height = 1.0 ; height <= 2.5 ; height += 0.5)
- {
- // Create new box each cycle
- CBox tryBox(length, width, height);
- if((carton%tryBox < tryBox.Volume()) && // Carton waste < a candy box
- (tryBox % candy == 0.0) && // & no waste in candy box
- (tryBox/candy >= minCandiesPerBox)) // & candy box holds minimum
- cout << endl << endl
- << "Trial Box L = " << tryBox.GetLength()
- << " W = " << tryBox.GetWidth()
- << " H = " << tryBox.GetHeight()
- << endl
- << "Trial Box contains " << tryBox / candy << " candies"
- << " and a carton contains " << carton / tryBox
- << " candy boxes.";
- }
- }
- }
- cout << endl;
- return 0;
- }
首先来看该程序的结构。该程序被分为多个文件,这在C++(www.cppentry.com)编程(www.cppentry.com)中很常见。如果切换到Solution Explorer选项卡(见图8-13),就能够看到这些文件。Ex8_12.cpp文件包含main()函数和嵌入Box- Operators.h头文件的#include指令,而BoxOperators.h头文件包含BoxOperators.cpp文件中所有函数的原型(它们不是类成员)。Ex8_12.cpp文件还包含一条嵌入Box.h文件中CBox类定义的#include指令。C++(www.cppentry.com)控制台程序通常被分为多个文件,它们各自属于下列3个基本类别之一:
(1) 包含库文件#include指令、全局常量和变量、类定义以及函数原型的.h文件。换句话说,.h文件包含除可执行代码以外的一切。它们还包含内联函数的定义。当程序中有多个类定义时,通常将这些类分别放入单独的.h文件中。
(2) 包含程序的可执行代码的.cpp文件,其中还包含可执行代码所需全部定义的#include指令。
(3) 包含main()函数的另一个.cpp文件。
实际上不需要解释main()函数中的代码 -- 它们几乎就是对问题定义的直接文字表示,因为是类接口中的运算符对CBox对象执行面向问题的动作。
使用标准箱子这个问题的答案在main()函数开始部分的声明语句中,这些语句将所需的答案计算出来作为初始化值。然后,输出这些值,输出时添加了一些解释性的注释。