Operator Overloading
MC logo
 

Operator Overloading

Ada Code Examples


<<Simple Function 2 Download Skip and Read 2>>
--
-- This file uses operator overloading to move the & operator toward
-- actual usefulness.
--
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Gnat.Io; use Gnat.Io;
procedure Over is
   -- Convert integer to string.  Note that the return type is an
   -- array of indeterminite size.
   function ItoS(I: Integer) return String is
      Res: String(1..40);
      J: Integer;
   begin
      -- This writes I to the string Res, with lots of stupid, useless, and
      -- annoying leading spaces.
      Put(Res, I);

      -- Find end of the stupid leading spaces.
      J := Res'Last;
      loop
         exit when J < Res'First;
         exit when Res(J) = ' ';
         J := J - 1;
      end loop;

      -- Return the result.
      return Res(J + 1 .. Res'Last);
   end;

   -- Gives a meaning to string & integer.
   function "&" (S: String; I: Integer) return String is
   begin
      return S & ItoS(I);
   end;

   -- Gives a meaning to integer & string.
   function "&" (I: Integer; S: String) return String is
   begin
      return ItoS(I) & S;
   end;

   K: Integer;
begin
   Put("How much? ");
   Gnat.Io.Get(K);

   -- This outputs a line by concatenating strings and integers.  It
   -- actually involves calling the overloaded & functions.
   Put_Line(K & " is the square root of " & K*K &
            ", and half of " & 2*K & ".");
end over;
<<Simple Function 2 Skip and Read 2>>