1. Experiment purpose
(1) Learn the use of static members
(2) Learn the use of constant members
(3) Master the initialization of static data members and constant data members
2. Experiment content
(1) A store distributes a The goods are purchased in boxes and sold in boxes. The weight is used as the unit when purchasing and selling. The weight of each box is different. Therefore, the store needs to record the total weight of the goods currently in stock. Now it is required to design a Goods class and use static members to simulate the purchase and sale of goods in the store;
(2) Add a constant data member (goods name) to the above Goods class and initialize the goods name;
(3) Change the previous Rewrite some defined member functions as constant member functions and observe whether all member functions in the class can be set as constant member functions.
3. Experimental steps
(1) Add a header file Goods.h to define the Goods class
#include<iostream>using namespace std;class Goods {public: Goods(int inBox, double inWeight); ~Goods(); void Sell(int outBox, double outWeight); void print();private: int Box; double weight; static int totalBox; static double totalWeight; }; Goods::Goods(int inBox, double inWeight) { Box = inBox; totalWeight = inWeight; totalBox = totalBox + inBox; totalWeight = totalWeight = inWeight; }void Goods::Sell(int outBox, double outWeight) { totalBox = totalBox - outBox; totalWeight = totalWeight - outWeight; }void Goods::print() { cout << "当前货物总箱数为:" << totalBox << "箱" << endl; cout << "当前货物总重量为:" << totalWeight << "kg" << endl; } Goods::~Goods() { }int Goods::totalBox = 0;double Goods::totalWeight = 0.0;
(2) Add a source file Goods.cpp to implement the member function.
(3) Define several Goods class objects in the main program to simulate the process of purchasing and selling. View the running results.
#include"Goods.h"int main() { Goods gd(5, 200); gd.Sell(2, 50); gd.print(); getchar(); return 0; }
(4) Add a constant data member const char * name to the Goods class to represent the name of the goods, rewrite the constructor and main program calls, and assign an initial value to the goods name in the member initialization list of the constructor. Recompile and observe the running results.
(5) Rewrite some of the previously defined member functions as constant member functions and observe whether all member functions in the class can be set as constant member functions.
Constant data members cannot update the data members of the object, nor can they call ordinary member functions in the class. The value of data members will never be updated in a constant member function.