BotonMenu
BotonIndice

Visita : conoce3000.com
Paypal : https://www.paypal.com/donate/?hosted_button_id=XY8TZ3MGN64GE

PASCAL CON FREE PASCAL

PASCAL CON FREE PASCAL

PASCAL CON FREE PASCAL


10. INTRODUCCIÓN A LA PROGRAMACIÓN ORIENTADA A OBJETOS I.
10.4. SOBRECARGA DE MÉTODOS - POLIMORFISMO POR SOBRECARGA.
10. INTRODUCCIÓN A LA PROGRAMACIÓN ORIENTADA A OBJETOS I.
10.4. SOBRECARGA DE MÉTODOS - POLIMORFISMO POR SOBRECARGA.
10. INTRODUCCIÓN A LA PROGRAMACIÓN ORIENTADA A OBJETOS I.
10.4. SOBRECARGA DE MÉTODOS - POLIMORFISMO POR SOBRECARGA.

SIGUIENTE

SIGUIENTE

SIGUIENTE


‒ Sobrecarga de métodos - Polimorfismo por sobrecarga.

La sobrecarga de métodos es muy parecida a la sobrecarga de funciones, tal como se explico en el capítulo 6.5 sobrecarga de funciones y procedimientos, pero en este caso se usa con métodos y constructores, los destructores no se pueden sobrecargar ya que sólo debe haber uno por clase. Para sobrecargar métodos y constructores, estos sólo se deben diferenciar en la cantidad de parámetros o en el uso de parámetros con tipos de datos diferentes y usar el mismo nombre. También se puede usar la palabra reservada overload, pero esto no es necesario y sólo se mantiene por compatibilidad con delphi. Gracias a la sobrecarga de métodos, una clase puede tener distinto comportamiento dependiendo de cual método sobrecargado se use, a esta característica se le conoce como Polimorfismo por sobrecarga. La palabra Polimorfismo viene de la capacidad que tiene una clase de cambiar su comportamiento. En el caso del polimorfismo por sobrecarga, el cambio del comportamiento de una clase se define sobrecargando los métodos necesarios para lograr el polimorfismo.

El siguiente ejemplo es la unidad Complejos, al cual se le ha añadido un nuevo constructor Crear que sobrecarga el ya existente, este nuevo constructor permite crear un número imaginario puro, Ejemplo:


Descargar
{$codepage utf8}
{$mode objfpc}
Unit Complejos03;
Interface

Type
  TComplejo = class
    ParteReal,ParteImag:double;
    Constructor Crear(i:double); //sobrecargado, crea un imaginario puro
    Constructor Crear(r,i:double); //sobrecargado
    Function ObtReal:double;
    Function ObtImag:double;
    Procedure PonReal(n:double);
    Procedure PonImag(n:double);
    Function ObtCad(dec:integer):string;
    Function PonCad(n:string):integer;
    Procedure Adicion(n:TComplejo);
    Procedure Multiplicacion(n:TComplejo);
  End;

Implementation

    Constructor TComplejo.Crear(i:double);
      Begin
        ParteReal:=0;
        ParteImag:=i
      End;

    Constructor TComplejo.Crear(r,i:double);
      Begin
        ParteReal:=r;
        ParteImag:=i;
      End;

    Function TComplejo.ObtReal:double;
      Begin
        ObtReal:=ParteReal
      End;

    Function TComplejo.ObtImag:double;
      Begin
        ObtImag:=ParteImag
      End;

    Procedure TComplejo.PonReal(n:double);
      Begin
        ParteReal:=n;
      End;

    Procedure TComplejo.PonImag(n:double);
      Begin
        ParteImag:=n
      End;

    Function TComplejo.ObtCad(dec:integer):string;
      var aux1,aux2,p:string;
      Begin
        p:='';
          Str(ParteReal:0:dec,aux1);
          Str(ParteImag:0:dec,aux2);
        if ParteImag>=0 then p:='+';
          ObtCad := aux1 + p +  aux2 + 'i';
      End;

      Function TComplejo.PonCad(n:string):integer;
      Var aux:string;
          p,i,error:integer;
          PR,PI:string;
          encontro:boolean;
      Begin
       aux:=n;
       ParteReal:=0;
       ParteImag:=0;
       error:=0;
       if (aux[length(aux)]='i') and (Not(aux[length(aux)-1]in['0'..'9']))
          then aux:=Copy(aux,1,length(aux)-1)+'1i';
       if aux[length(aux)]='i' then
         Begin
           delete(aux,length(aux),1);
           if aux[length(aux)] in ['0'..'9']
              then Begin
                     i:=length(aux);
                     encontro:=false;
                     p:=0;
                     while (not encontro) and (i>1) do
                      Begin
                       if (aux[i]='+') or (aux[i]='-')
                         then Begin
                               encontro:=true;
                               p:=i
                              end;
                       i:=i-1
                      End;
                     PR:=Copy(aux,1,p-1);
                     delete(aux,1,p-1);
                     PI:=aux;
                     Val(PR,ParteReal,error);
                     Val(PI,ParteImag,error);
                     if error<>0 then
                       Begin
                         ParteReal:=0;
                         ParteImag:=0
                       End
                   End;
         End
       else
        Begin
         Val(aux,ParteReal,error);
        End;
       PonCad:=error
      End;


    Procedure TComplejo.Adicion(n:TComplejo);
      Begin
        PonReal(ObtReal+n.ObtReal);
        PonImag(ObtImag+n.ObtImag)
      End;

    Procedure TComplejo.Multiplicacion(n:TComplejo);
      var PR,PI:double;
      Begin
       PR:=(ObtReal*n.ObtReal)-(ObtImag*n.ObtImag);
       PI:=(ObtReal*n.ObtImag)+(ObtImag*n.ObtReal);
       PonReal(PR);
         PonImag(PI)
      End;

End.
Código fuente 7: Unidad Complejos03 con el cosntructor Crear sobrecargado.
Descargar

El siguiente programa hace uso de la unidad Complejos con los constructores sobrecargados:


Descargar
{$codepage utf8}
{$mode objfpc}
Uses Complejos03;
Var A,B:TComplejo;

Begin
   A:=TComplejo.Crear(10,4);
   B:=TComplejo.Crear(1);
   Writeln('A=',A.ObtCad(0));
   Writeln('B=',B.ObtCad(0))
End.
Código fuente 8: Uso de la unidad complejos03 con los constructores sobrecargados.
Descargar




SIGUIENTE
SIGUIENTE
SIGUIENTE


 
‒ Comentarios y sugerencias.

Agradezco de antemano, todo comentario, sugerencia, y donativo a través de , que ayude a mejorar los contenidos educativos de Conoce 3000. Además, cualquier pregunta o duda que tengas lo puedes hacer por este medio. Pero, todo contenido que pueda resultar ofensivo, malicioso, racista, sexista, discriminatorio, obsceno, vulgar será eliminado. Para clases particulares contactame por whatsapp al 📲 (+51) 999 264 073








PORTADA |  INTERESANTE |  APUNTES |  LIBROS |  GALERIA


Creative Commons License


Todos los textos, imágenes y videos de Conoce3000 estan colocados bajo una licencia : Creative Commons Reconocimiento-NoComercial 3.0 Unported License.