gpt4 book ai didi

inheritance - D:覆盖子类中的 opDispatch

转载 作者:行者123 更新时间:2023-12-04 02:29:35 25 4
gpt4 key购买 nike

有什么方法可以覆盖子类中的 opDispatch 吗?我真正想要做的是传递一个以父类(super class)作为其静态类型的变量,但是它将对 opDispatch 的调用重定向到它的子类型(动态类型)。

基本上,我希望这段代码打印“Sub”而不是“Super”。

import std.stdio;

class Super
{
void opDispatch(string m)()
{
writeln("Super");
}
}

class Sub : Super
{
override void opDispatch(string m)()
{
writeln("Sub");
}
}

void main()
{
Super s = new Sub();
s.callingOpDispatch; // Writes "Super" instead of "Sub"
}

我傻眼了,因为我不能强制编译器通过使用抽象方法来查找方法覆盖(D 不允许抽象模板化方法)。

PS:有人可以创建标签 opDispatch 吗? (在我看来这对D有好处?)

最佳答案

成员模板函数不能是虚拟的,因此不能被覆盖。

http://dlang.org/function.html#virtual-functions

opDispatch 是模板函数。这两个调用是相同的:

s.callingOpDispatch();
s.opDispatch!("callingOpDispatch")()

关于inheritance - D:覆盖子类中的 opDispatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18209695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com