首页 > 解决方案 > 多态行为

问题描述

有人可以帮助解释这种行为差异吗?虚拟的功能不应该总是虚拟的吗?在哪里制作虚拟父/子类是否重要。

变体 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

https://www.edaplayground.com/x/3RMZ

标签: polymorphismsystem-verilog

解决方案


在变体 2 中,A::showMsg是非虚拟的。代码调用a.showMsg必须表现为非虚拟的,因为它不知道类将被扩展。这意味着A::showMsg可以有一个完全不同的原型,B::showMsg如果你想要的话(即不同数量的参数)。但是一旦B::showMsg被声明为虚拟,所有派生方法都是虚拟的,并且必须具有相同的原型。


推荐阅读