简体   繁体   English

FreePascal Lazarus中的继承

[英]Inheritance in FreePascal Lazarus

I'm learning free pascal using the Lazarus IDE and I don't know how to inheritance methods in the derived form. 我正在使用Lazarus IDE学习免费的pascal,而且我不知道如何继承派生形式的方法。

I want something like this: 我想要这样的东西:

Form base or father: 表格基础或父亲:

procedure HelloWorld;
begin
 ShowMessage('Hello World from base form or father');
end;

and form derived or child: 以及衍生形式或子形式:

procedure HelloWorld;
begin
  inherited;
  ShowMessage('Hello World from derived form or child');
end;

I want the result shows 2 messages by clicking (eg Button1) 我希望结果通过单击显示2条消息(例如Button1)

Thanks!!! 谢谢!!!

For a better appreciation of the Object Pascal language, i believe you should start by reading the freepascal reference guide. 为了更好地了解Object Pascal语言,我相信您应该先阅读FreePascal参考指南。 FreePascal is the underlaying compiler below lazarus. FreePascal是lazarus之下的底层编译器。

Its important to understand that Forms, Labels, Buttons, etc, are specific incarnations of the concepts of objects, instances, classes etc. 理解表单,标签,按钮等是对象,实例,类等概念的特定化身,这一点很重要。

In that regard, a class is a structure binding code and data. 在这方面,类是绑定代码和数据的结构。 What you want to achieve is something like this : 您想要实现的是这样的:

Type
TMyClass = Class(<ancestorclass>)
<fields and methods>
End;

TMyChildClass = Class(TMyClass)
<fields and methods>
End;

This means that TMyChildClass is a class derived from TMyClass. 这意味着TMyChildClass是从TMyClass派生的类。 In the event that you have methods in both classes with same name, you can use the keyword "override" to show the compiler that that method was overriden by the child class, like this : 如果两个类中的方法名称相同,则可以使用关键字“ override”来向编译器显示该方法被子类覆盖,如下所示:

TMyClass = Class /* No parenthesis or ancestor name means the class derives from TObject */
Procedure ParentMethod;
End;

TMyChildClass = Class(TMyClass)
Procedure ParentMethod; Override;
End;

Procedure TMyClass.ParentMethod;
Begin
 DoSomething;
End;

Procedure TMyChildClass.ParentMethod; /* Dont repeat the override */
Begin
 Inherited; // This will call the parents method
End;

This is the proper way to do method override in object pascal. 这是在对象pascal中进行方法重写的正确方法。 If the definition of the class where you want to use "inherited" has no parenthesis and the name of the ancestor class, theres no ancestry relation between then and inherited will not do what you are expecting to do. 如果要在其中使用“继承”的类的定义没有括号,并且祖先类的名称不存在,那么在继承和继承之间就没有祖先的关系将无法满足您的期望。

In Pascal procedure is not an object oriented programming construct. 在Pascal中, procedure不是面向对象的编程构造。

FreePascal includes objects and objects can include procedures: FreePascal包含对象,并且对象可以包含过程:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM