fork download
  1.  
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. class Figure {
  6. protected:
  7. double x, y;
  8. public:
  9. void setDim(double i, double j) {
  10. x = i;
  11. y = j;
  12. }
  13. virtual void showArea() = 0; // чисто віртуальна
  14. };
  15.  
  16. class Triangle: public Figure {
  17. public:
  18. void showArea() {
  19. cout << "Triangle with height ";
  20. cout << x << " and base " << y;
  21. cout << " has an area of ";
  22. cout << x * 0.5 * y << ".\n";
  23. }
  24. };
  25.  
  26. class Square: public Figure {
  27. public:
  28. void showArea() {
  29. cout << "Square with dimensions ";
  30. cout << x << "x" << y;
  31. cout << " has an area of ";
  32. cout << x * y << ".\n";
  33. }
  34. };
  35.  
  36. class Circle: public Figure {
  37. // визначення showArea() відсутнє, і тому виникає помилка
  38. };
  39.  
  40. int main() {
  41. Figure *p; // створення вказівника базового типу
  42. //Circle c; // спроба створення об'єкта типу Circle - ПОМИЛКА
  43. Triangle t; // створення об'єктів похідних типів
  44. Square s;
  45.  
  46. p = &t;
  47. p->setDim(10.0, 5.0);
  48. p->showArea();
  49.  
  50. p = &s;
  51. p->setDim(10.0, 5.0);
  52. p->showArea();
  53. Figure **x=new Figure*[2];
  54. x[0]=&t;
  55. x[1]=&s;
  56. for( int i=0;i<2;i++){
  57. x[i]->showArea();
  58.  
  59. }
  60.  
  61. return 0;
  62. }
Success #stdin #stdout 0s 5336KB
stdin
Standard input is empty
stdout
Triangle with height 10 and base 5 has an area of 25.
Square with dimensions 10x5 has an area of 50.
Triangle with height 10 and base 5 has an area of 25.
Square with dimensions 10x5 has an area of 50.