Инструменты пользователя

Инструменты сайта


start:prog2:lectures:code6
Полиморфизм
// Programming 1. Sample at 2017-05-18-14-42.35
#include <stdio.h>
 
struct Shape
{
  virtual double s()=0;
};
 
struct Circle : public Shape
{
  Circle() {m_radius = 1.0;}
  double m_radius;
  double s() { return m_radius*m_radius*3.1415926536; }
};
 
struct Square : public Shape
{
  Square() { m_side = 2.0;}
  double m_side;
  double s() { return m_side*m_side; }
};
 
struct Triangle : public Shape
{
  Triangle() {m_base = m_hight = 4.0;}
  double m_base;
  double m_hight;
 
  double s() {return m_base*m_hight/2.0;}
 
};
 
 
int main(/*int c, char **v */)
{
  Shape* objects[4];
  Shape s;
 
  objects[0] = new Circle;
  objects[1] = new Circle;
  objects[2] = new Triangle;
  objects[3] = new Square;
 
  double s = 0.0;
  for(int i=0;i<4; ++i)
  {
    s+= objects[i]->s();
  }
  printf("Total: %lf\n",s);
 
  return 0;
}