C++/Class/Abstract Class

Материал из C\C++ эксперт
Перейти к: навигация, поиск

abstract base class

<source lang="cpp">

  1. include <iostream>

using namespace std; class CPolygon {

 protected:
   int width, height;
 public:
   void set_values (int a, int b)
     { width=a; height=b; }
   virtual int area (void) =0;

}; class CRectangle: public CPolygon {

 public:
   int area (void)
     { return (width * height); }

}; class CTriangle: public CPolygon {

 public:
   int area (void)
     { return (width * height / 2); }

}; int main () {

 CRectangle rect;
 CTriangle trgl;
 CPolygon * ppoly1 = &rect;
 CPolygon * ppoly2 = &trgl;
 ppoly1->set_values (4,5);
 ppoly2->set_values (4,5);
 cout << ppoly1->area() << endl;
 cout << ppoly2->area() << endl;
 return 0;

}


 </source>


Create an abstract class.

<source lang="cpp">

  1. include <iostream>

using namespace std; class area {

 double dim1, dim2; 

public:

 void setarea(double d1, double d2)
 {
   dim1 = d1;
   dim2 = d2;
 }
 void getdim(double &d1, double &d2)
 {
   d1 = dim1;
   d2 = dim2;
 }
 virtual double getarea() = 0; // pure virtual function

}; class rectangle : public area { public:

 double getarea() 
 {
   double d1, d2;
 
   getdim(d1, d2);
   return d1 * d2;
 }

}; class triangle : public area { public:

 double getarea()
 {
   double d1, d2;
 
   getdim(d1, d2);
   return 0.5 * d1 * d2;
 }

}; int main() {

 area *p;
 rectangle r;
 triangle t;
 r.setarea(3.3, 4.5);
 t.setarea(4.0, 5.0);
 p = &r;
 cout << "Rectangle has area: " << p->getarea() << "\n";
 p = &t;
 cout << "Triangle has area: " << p->getarea() << "\n";
 return 0;

}


 </source>


pure virtual members can be called from the abstract base class

<source lang="cpp">

  1. include <iostream>

using namespace std; class CPolygon {

 protected:
   int width, height;
 public:
   void set_values (int a, int b)
     { width=a; height=b; }
   virtual int area (void) =0;
   void printarea (void)
   { cout << this->area() << endl; }

}; class CRectangle: public CPolygon {

 public:
   int area (void)
   { return (width * height); }

}; class CTriangle: public CPolygon {

 public:
   int area (void)
   { return (width * height / 2); }

}; int main () {

 CRectangle rect;
 CTriangle trgl;
 CPolygon * ppoly1 = &rect;
 CPolygon * ppoly2 = &trgl;
 ppoly1->set_values (4,5);
 ppoly2->set_values (4,5);
 ppoly1->printarea();
 ppoly2->printarea();
 return 0;

}


 </source>