Wednesday, January 13, 2016

Overriding in C++ si PHP

"Implement 2 classes Square and Rectangle that inherit the Shape class and override the function Area."

In acest enunt luat de pe programmr.com cerinta nu este, in mod explicit, de a folosi o clasa de baza PHP abstracta (se putea adauga un corp vid al functiei Area(), {}, in clasa Shape, renuntand la cuvantul-cheie "abstract" ) dar am optat pentru aceasta din motive de "rodaj" al sintaxei. 

De asemenea, inaintea de a prezenta rezolvarea, am considerat util un reminder al sintaxei de derivare si al mecanismului de overriding in PHP si in C++ in doua exemple simple:


1) overriding in PHP:

<?php

// Overriding
class A
{
private $a;
function __construct($a1 = 0)
{
if(is_numeric($a1))
{
$this->a = $a1;
}
}
function Getter()
{
echo "Membri privati ai clasei:\n";
echo $this->a;
}
}

class B extends A
{
private $b;
function __construct($a1 = 0, $b1 = 0)
{
if(is_numeric($b1))
{
parent::__construct($a1);
$this->b = $b1;
}
}
function Getter()
{
parent::Getter();
echo "\n".($this->b);
}
}

$o1 = new A(13);
$o1->Getter();
echo "\n";
$o2 = new B(14, 15);
$o2->Getter();
?>









2) aceeasi situatie tratata in C++:

// overriding

#include <iostream>

using namespace std;

class A
{
      int a;
      public:
      A(int a1 = 0) : a(a1) {}
      void Getter()
      {
       cout << "Membri privati ai clasei:\n";
       cout << a <<"\n";
      }
};

class B : public A

{
      int b;
      public:
      B(int a1 = 0, int b1 = 0) : A(a1), b(b1) {}
      void Getter()
      {
           A::Getter();
           cout << b <<"\n";
      }
};

int main()
{
    A o1(13);
    B o2(14, 15);
    o1.Getter();
    o2.Getter();
    return 0;
}













In fine, rezolvarea problemei de pe programmer.com, printscreenul si link-ul pentru codul rulat direct pe site:

<?php

abstract class Shape
{
 abstract function Area();
}

class Rectangle extends Shape
{
 private $length;
 private $breadth;
 function __construct($l1 = 0, $l2 = 0)
 {
  if(is_numeric($l1) && is_numeric($l2))
  {
   $this->length = $l1;
   $this->breadth = $l2;
  }
 }
 function Area() {return ($this->length)*($this->breadth);}
}

class Square extends Shape
{
 private $side;
 function __construct($l1 = 0)
 {
  if(is_numeric($l1)) $this->side = $l1;
 }
 function Area() {return ($this->side)*($this->side);}
}

echo "Select one option:\n1. Area of Rectange 2. Area of Square :";

$select = trim(fgets(STDIN));

if(is_numeric($select) && $select == 1)
{
 echo "Enter Length:";
 $l1 = trim(fgets(STDIN));
 echo "Enter Breadth:";
 $l2 = trim(fgets(STDIN));
 $o1 = new Rectangle($l1, $l2);
 echo "Area of Rectangle:".($o1->Area());
}
else if(is_numeric($select) && $select == 2)
{
 echo "Enter Side:";
 $l1 = trim(fgets(STDIN));
 $o2 = new Square($l1);
 echo "Area of Square:".($o2->Area());
}
else echo "Invalid option";

exit;


?>


















Link-ul, aici.

No comments:

Post a Comment