1, the purpose of the experiment
(1) Use of learning static members
(2) Use of regular members of learning
(3) Initialization of static data members and constant data members
2. Experimental content
(1) A store distributes a kind of goods, goods into boxes to buy, into boxes to sell, buy and sell in weight units, the weight of each box is different, therefore, the store needs to record the current inventory of the total weight of the goods, now requires the design of a goods class and use static members to simulate the purchase and sale of the store goods;
(2) Add a regular data member (the goods name) for the goods class above, and initialize the name of the goods;
(3) Override some of the previously defined member functions as constant member functions to see if all of the member functions in the class can be set to a constant member function.
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 ();p rivate: 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::p rint () { cout << "Current total box of goods:" << totalbox << "box" << Endl; cout << "Current total weight of goods:" << 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 objects of goods class in the main program, simulating the process of purchase and sale. View the results of the run.
#include "Goods.h" int main () { Goods gd (5, +); Gd. Sell (2, +); Gd.print (); GetChar (); return 0;}
(4) Add a constant data member const char * name to the goods class to represent the cargo name, rewrite the constructor and the main program's call, and assign an initial value to the cargo name in the constructor's member initialization list. Recompile and observe the results of the operation.
(5) Override some of the previously defined member functions as constant member functions to see if all of the member functions in the class can be set to a constant member function.
A constant data member cannot update a data member of an object, nor can it call a normal member function in that class. The value of the data member is never updated in the constant member function.