polymorphism - 多态行为
问题描述
有人可以帮助解释这种行为差异吗?虚拟的功能不应该总是虚拟的吗?在哪里制作虚拟父/子类是否重要。
变体 1:
module test;
class A;
virtual function void showMsg(int val);
$display("This is A");
endfunction
endclass
class B extends A;
function void showMsg(int val);
$display("This is B, val = %0d", val);
endfunction
endclass
class C extends B;
function void showMsg(int val);
$display("This is C, val=%0d", val+1);
endfunction
endclass
initial begin
A a;
B b;
C c;
b = new();
a = b;
a.showMsg(1);
c = new();
b = c;
b.showMsg(7);
end
endmodule
变体 2:
module test;
class A;
function void showMsg(int val);
$display("This is A");
endfunction
endclass
class B extends A;
virtual function void showMsg(int val);
$display("This is B, val = %0d", val);
endfunction
endclass
class C extends B;
function void showMsg(int val);
$display("This is C, val=%0d", val+1);
endfunction
endclass
initial begin
A a;
B b;
C c;
b = new();
a = b;
a.showMsg(1);
c = new();
b = c;
b.showMsg(7);
end
endmodule
Variant1 结果-
这是 B,val = 1 这是 C,val=8
Variant2 结果-
这是 A 这是 C,val=8
解决方案
在变体 2 中,A::showMsg
是非虚拟的。代码调用a.showMsg
必须表现为非虚拟的,因为它不知道类将被扩展。这意味着A::showMsg
可以有一个完全不同的原型,B::showMsg
如果你想要的话(即不同数量的参数)。但是一旦B::showMsg
被声明为虚拟,所有派生方法都是虚拟的,并且必须具有相同的原型。
推荐阅读
- .htaccess - 从本地主机访问服务器数据时出现 CORS 问题
- c# - 框架升级后似乎与 IIS 中的应用程序池问题相关的错误和警告
- tensorflow - 为什么在应用 vggnet 时这不太准确?
- java - 尝试运行犯罪意图后应用程序崩溃
- javascript - 这是在 redux 中实现中间件的正确方法吗?
- json - ECS任务定义容器json中的Docker动态环境变量
- google-app-engine - 在本地数据存储控制台上按类型查看多个属性
- javascript - path.basename 应用于目录?
- amazon-web-services - 需要 AWS 网站后端的指导
- mongodb - MeteorJS queries are super slow if users have active sessions