Abstract function in Pascal

限于喜欢 提交于 2019-12-13 00:31:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!