Two-edged sword in OOP

xiaoxiao2021-03-06  108

in conclusion:

1, OO is a kind of belief ...

2, OO is absolutely profound ....

/

A few days ago, I saw a very famous commercial control source code and found a very interesting usage:

Integer (xxx): = aaa;

TTTT (XXX): = BBB;

Detail taste, found that this usage often can receive unexpected effects:

such as:

TTESTREC = Record A, B, C: integer; end;

TTESTCLS = Class Private finner: TTESTREC; FREADONLYVALUE: INTEGER;

Function GetNewNer: Ptertainment GetNewinner: TTESTREC READ FINNER WRITE FINNER; Property Newinner: PTESTREC ReadNewNNer; Property ReadonlyValue;

You will find that you can't change AtestCls.inner.a (compile time Delphi directly, because two Recode assignments in Delphi 7 are Copy Memory rather than simple "inventory"!

Procedure TForm1.Button1Click (Sender: Tobject); Begin with TTestcls.create Do Try // Inner.a: = 10; CAPTION: = TButton (Sender) .caption 'A: =' INTOSTR (Inner.a); Finally .

However, if we know that Delphi is compiled directly Finner when visiting this Inner, then combines the above interesting usage:

Procedure TForm1.Button3Click (Sender: Tobject); VAR P: ​​Pinteger; Begin with TTESTCLS.CREATE DO TRY P: = @ (Inner.a); Integer (p ^): = 100; Caption: = Tbutton (Sender) .caption 'A: =' INTOSTOSTR (Inner.a); Finally Free; end; end;

Further, the use of pointers can break through OO to Private protection:

Procedure TForm1.Button4Click (Sender: Tobject); VAR P: ​​Pinteger; Begin with TTESTCLS.CREATE DO TRY P: = @ (ReadonlyValue); Integer (P ^): = 1000; Caption: = TButton (Sender) .caption ' ReadonlyValue: = ' INTOSTR (READONLYVALUE); FINALLY FREE; END;

As for "睬 过 过", then nothing is below:

Procedure TForm1.Button5Click (Sender: Tobject); VAR P1, P2: Pinteger; Begin with TTestcls.create Do Try P1: = @ (Inner.a); // Memory FINNER and FREADONLYVALUE is actually only TTESTREC Size byte INTEGER (p2): = Integer (p1) sizeof (TTESTREC); Integer (p2 ^): = 100; caption: = tbutton (sender) .caption 'readonlyValue: =' INTOSTR (READONLYVALUE); FINALLY FREE; END; of course, pointers can not only destroy OO, but also make your code more OO:

TTESTREC = Record A, B, C: Integer; end; ptestrec = ^ TTESTREC;

TTESTCLS = Class Private finner: TTESTREC; FREADONLYVALUE: INTEGER;

Function GetNewNer: Ptertainment GetNewinner: TTESTREC READ FINNER WRITE FINNER; Property Newinner: PTESTREC ReadNewNNer; Property ReadonlyValue;

Procedure TFORM1.BUTTON2CLICK (Sender: Tobject); Begin with TTESTCLS.CREATE DO TRY newinner.a: = 10; Caption: = tbutton (sender) .caption 'A: =' INTOSTR (Inner.a); Finally Free; END;

Take a look at the non OO code in realities:

Using the "Pointer Scheme" to change Txxx to PXXX, it didn't have a little impact on the original code, but make it more oo ...

转载请注明原文地址:https://www.9cbs.com/read-98038.html

New Post(0)