Home > Back-end >  Ask a question
Ask a question

Time:09-18

Declare a graphics class Figure, it contains two pure virtual function area () and volume (),
Used to calculate the area (or area) and volume, type of Figure public derived subclass round Circle,
It has a private member variable radius radius. And to access the public member functions of the radius setR ()
And getR (), the Circle area and cannot calculate volume can be calculated by derived classes Circle public
The two subclasses, ball Sphere and Cylinder Cylinder, Cylinder class contains
Private member variables high height. The ball and the cylinder can be calculated area (surface area) and body
Product, in the main function in the main, a statement of ball and cylinder objects of sp and cy, via
Figure of the reference or pointer to Figure calculate and output the two object surface and the body
Product, show the polymorphism of object-oriented program design,
This how to write

CodePudding user response:

 # include & lt; Iostream> 
using namespace std;

The class Figure {
Public:
Virtual float area ()=0;
Virtual float volume ()=0;
};
# # ifndef PI
# define PI 3.1415926
# endif
The class Circle: public Figure {
Public:
Void setR (const int the radius) {
This - & gt; The radius=radius;
};
Const int getR () {
Return the radius.
};
Float area () {
Radius, return PI * * radius;
}
Float volume () {
return 0;
}
Private:
Int the radius;
};
The class Sphere: public Circle {
Public:
Float area () {
The return Circle: : area () * 4;
}
Float volume () {
Return 4.0/3.0 * PI * getR getR () * () * getR ();
}
};
The class Cylinder: public Circle {
Public:
Float area () {
The return Circle: : area () * 2 + 2 * PI * getR () * height;
}
Float volume () {
The return Circle: : area () * height;
}
Void setH (const int height) {
This - & gt; Height=height;
};
Private:
Int height;
};
Void out (Figure & amp; Fi) {
Cout<" Area: "& lt; };
Int main (int arg c, char * argv []) {
Sphere sp;
Cylinder cy.
Sp. SetR (3);
Cy. SetR (3);
Cy. SetH (3);
Out (sp);
Out (cy);
return 0;
};
  • Related