How to define an operator in pascal
In my program, I need to get percentages often in code. At the moment I have this function to solve it
function percent(whole, part: double):double;
begin
percent:= whole * part / 100;
end;
I was wondering if there is a way to make a new statement so that I can only write something like: a: = 100% 20 and get the desired result. It would also have to be used like: c: = b / a; or: c: = c / a;
source to share
You can define operators in pascal, but only by their notation type. It's called operator overloading and you can read it here . What you do is define your own record type data and then overload the standard operators like = <>% etc. to do what you want them to do. Here's a simple example:
Interface
Type
TMyFloatType = record
value: Extended;
class operator Implicit(n: Extended): TMyFloatType;
class operator Explicit(n: Extended): TMyFloatType;
class operator Equal(a, b: TMyFloatType): Boolean;
class operator GreaterThan(a, b: TMyFloatType): Boolean;
end;
Implementation
class operator TMyFloatType.Implicit(n: Extended): TMyFloatType;
begin
result.value := n;
end;
class operator TMyFloatType.Explicit(n: Extended): TMyFloatType;
begin
result.value := n;
end;
class operator TMyFloatType.Equal(a, b: TMyFloatType): Boolean;
begin
result := (a.value = b.value);
end;
class operator TMyFloatType.GreaterThan(a, b: TMyFloatType): Boolean;
begin
result := (a.value > b.value);
end;
Then you can use this like regular variables:
procedure Test;
var
a, b: TMyFloatType;
Begin
// first assign some values to a and b
a := 3.14;
b := 2.7;
if a > b then
Begin
// Do something
End;
End;
Operators that you can overload also include mathematical operators, for example + - / * mod div
, etc.
Now that said, I find it would not be very convenient to implement this to avoid a simple function, but hey your choice.
It states that you can overload the operator to fulfill your bets. I believe that in order to calculate, for example, percentage := a % 20;
you need to overload the modulus operator.
source to share