父类在另一个类中
好的,我有这个类,比如说 CMain,它包含一个 CFruit 类。我想做的是根据 CFruit 的类型运行函数(如果是 CPear 或 CApple 等)。所以我想做这样的事情:
type CMain = class
myFruit : CFruit;
function GetFruit() : CFruit;
procedure SetFruit( Fruit : CFruit );
end;
procedure CMain.SetFruit( Fruit : CFruit );
begin
if Fruit.IsPear then .. else etc;
end;
...显然编译器阻止我这样做,因为 CFruit 只是 CPear 和 CApple 的父级。我有什么可行的方法可以做到这一点吗? (不可能制作单独的 CMain)。谢谢。
Okay, so I have this class, let's say CMain, that contains a CFruit class. What I would like to do is run functions based on CFruit's type (if it's CPear or CApple, etc). So I'd like to do something like this:
type CMain = class
myFruit : CFruit;
function GetFruit() : CFruit;
procedure SetFruit( Fruit : CFruit );
end;
procedure CMain.SetFruit( Fruit : CFruit );
begin
if Fruit.IsPear then .. else etc;
end;
...obviously the compiler stops me from doing this because CFruit is just CPear and CApple's parent. Is there any viable way I can do this? (making sepparate CMain's is out of the question). Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
IIUC 你想要虚拟方法。
IIUC you want virtual methods.
实际上有一个“is”运算符,它将检查对象是否是类的实例或其祖先。这称为“动态类型检查”并且有点高级。检查帮助以获得说明。
根据您的需求,“虚拟方法”可能就是您所需要的,正如其他人所解释的那样。请检查发布的有关“虚拟方法”的链接作为正确的 OOP 方式。
在下面的例子中
和
都返回 true
Actually there is an "is" operator, that will check if the Object is an instance of class or it's ancestors. This is called "dynamic type checking" and is sorta advanced. Check the help for a clarification.
Depending on your needs "virtual methods" could be what you need as explained by others. Please check the link posted about "virtual methods" as the correct OOP way.
In the example below
and
both return true
下面是一个使用虚方法的例子:
Here is an example for the use of virtual methods: