Forum > General

operators overloads working only one way?

(1/4) > >>

jamie:

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---unit Unit1; {$mode objfpc}{$H+} interface uses  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls; type   { TForm1 }   TForm1 = class(TForm)    Button1: TButton;    procedure Button1Click(Sender: TObject);  private   public   end; var  Form1: TForm1;operator := (A:TStream):Byte;operator := (A:Byte):TStream;implementationoperator :=(A:TStream):Byte;Begin A.Read(Result,1);End;operator :=(A:byte):Tstream;Begin   Result.Write(A,1);End;{$R *.lfm} { TForm1 } procedure TForm1.Button1Click(Sender: TObject);var  B:Byte;  S:TMemoryStream;begin  S:= TMemoryStream.Create;  S :=B; //<<<< nope  B:= S; //ok  S.Free;end; end.  
What em I doing wrong here?

 It works well only one way, the other way the compiler chokes.

Martin_fr:
I haven't run your code, but...


--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---operator :=(A:byte):Tstream;Begin   Result.Write(A,1);End;
Result is not initialized. So it will contain trash, and you get an access violation, or other random error.

You are assuming that you will always get the actual memory of the target variable. But that is not the case. (afaik by design)

jamie:
the problem is the compiler won't pass it.

it's not a runtime error, it's a compile time error.

So how do I adjust that so the compiler will accept it?

If i get runtime errors due to uncreated object then that is my fault?


Thaddy:
The compiler won't allow this, because the assignment operator the other way around is already taken and you can not override that.
Tip: in such cases I tend to override one of the less used set operators, when deemed safe, like ><
 The result is not created... how can it return a valid value...?

Martin_fr:
Because it is a different class. It has to be exact. (No idea if by design /  I found it by trial and error)

So either make an operator on TMemoryStream, or make/cast the variable TStream.

But, test it with diff settings (optimizations). And maybe ask the fpc team. I am not sure it is safe or will work as expected.

Navigation

[0] Message Index

[#] Next page

Go to full version