[fpc-pascal] Operators for a class
Sven Barth
pascaldragon at googlemail.com
Thu Dec 31 17:42:31 CET 2020
Am 31.12.2020 um 17:26 schrieb Gabor Boros via fpc-pascal:
> Hi All,
>
> I try to convert some C++ source to FPC, see below a short example
> from it. How can I define same operator with FPC trunk?
>
> class Cla
> {
> INT64 Num;
>
> public:
> Cla operator +(const Cla& m)
> {
> Cla ret(this);
>
> ret.Num += m.Num;
>
> return ret;
> }
Depending on the usecase of that class it might be better to declare it
as a record, then you can declare the operator as an operator in Pascal
as well (in C++ class and struct are rather interchangeable with the
main difference being the default visibility (private for class and
public for struct)):
=== code begin ===
// interface section
type
Cla = record
Num: Int64;
class operator + (const aLeft, aRight: Cla): Cla;
end;
// implementation section
class operator Cla.+(const aLeft, aRight: Cla): Cla;
begin
Result := Default(Cla);
Result.Num := aLeft.Num + aRight.Num;
end;
=== code end ===
Otherwise you need to declare a global operator overload (which will not
work with generics):
=== code begin ===
// in interface section
operator + (aLeft, aRight: TCla): TCla;
// in implementation section
operator +(aLeft, aRight: TCla): TCla;
begin
Result := TCla.Create;
Result.Num := aLeft.Num + aRight.Num;
end;
=== code end ===
Please note that in both cases the operators in Pascal are static
functions, not member methods.
Regards,
Sven
More information about the fpc-pascal
mailing list