C++ introductory tutorial — 19C ++ classes and objects

This is to better describe the nature of objects, so there are classes and objects.

Example: class Box {public: double length; // a double width; // Box width double height; // Box height}; The class is defined with class, includes this with {}, and then writes attributes.

Class usage. When a class is defined, it can be used as a data type, as follows: Box Box1; // declare Box1 with type Box Box Box2; // declare Box2 of type Box

// Box1 and Box2 are called objects.

#include <iostream>
 
using namespace std;
 
class Box
{
   public:
      double l;   / / the length
      double w;  / / width
      double h;   / / height
};
 
int main( )
{
   Box Box1;        // declare Box1 of type Box
   Box Box2;        // declare Box2 of type Box
   double v = 0.0;     // Used to store volume
 
   // box 1 details
   Box1.h= 5.0; 
   Box1.l= 6.0; 
   Box1.w= 7.0;
 
   // box 2 details
   Box2.h= 10.0;
   Box2.l= 12.0;
   Box2.w= 13.0;
 
   // The volume of box 1
   v = Box1.h* Box1.l* Box1.w;
   cout << "Box1 volume:" << v <<endl;
 
   // The volume of box 2
   v = Box2.h* Box2.l* Box2.w;
   cout << "Box2 volume:" << v <<endl;
   return 0;
}
Copy the code