问题
I have been working on AVL-tree unit where user can specify what he wants to have inside of the tree. I'm using objects for this purpose. In my unit I defined parent Object called Node and pointer to this object is PTNode. In this object I have 3 attributes which are Balance:integer;Left,Right:PTNode for sons of the node, and 1 method:Function Is_Greater(Node1:PTNode):integer which is virtual and abstract. And it is left up to user to define this function(I don't know whether it will be char or integer etc).
I was trying to test this unit and I came across one problem. I created child object of my object Node called Object1=Object(Node) and added one attribute X:integer and I want to define the Function Is_Greater. Here is the declaration and part of code:
Unit
Unit Tree;
interface
type PTNode=^Node;
Node=object
Left,Right:PTNode;
Balance:integer;
Function Is_Greater(Node1:PTNode):integer; virtual; abstract;
end;
after this I list and implement functions in my unit which are not that relevant to my problem.
This is my test program:
Program Test;
uses Tree;
Type PTObject=^Object1;
Object1=object(Node)
X:integer;
Function Is_Greater(Node1:PTNode):integer; virtual;
end;
Function Object1.Is_Greater(Node1:PTNode):integer;
begin
if X>Node1^.X then Is_Greater:=1
else if X<Node1^.X then Is_Greater:=-1
else Is_Greater:=0;
end;
and it gives me error saying that X is not part of Object Node. But when I try to set Node1:PTObject then it gives me error that my function doesn't match its parent. I don't know how to solve this.
回答1:
You need to type cast the argument Node1
:
if X>PTObject(Node1)^.X then Is_Greater:=1
else if X<PTObject(Node1)^.X then Is_Greater:=-1
else Is_Greater:=0;
来源:https://stackoverflow.com/questions/32416605/abstract-function-in-pascal