此示例粘贴自 1800-2009 SystemVerilog 规范的第 8.13 节,该规范解释了该问题。我的观点是,像这样覆盖班级成员是一个非常糟糕的主意。规范中的示例只是为了说明它是如何工作的。
类属性integer i
在基类和子类中都定义。此声明LinkedPacket
覆盖并隐藏Packet
.
从规范:
在这种情况下,对 p 的引用访问 Packet 类的方法和类属性。因此,例如,如果 LinkedPacket 中的类属性和方法被覆盖,那么这些通过 p 引用的被覆盖的成员将获得 Packet 类中的原始成员。从 p 开始,LinkedPacket 中的新成员和所有被覆盖的成员现在都被隐藏了。
Since you are calling the function through a handle to Packet
you get the values from Packet
.
In addition, the get()
function is not declared virtual
. This is why you do not see the integer being negated. This is also noted in the example in the specification.
To call the overridden method via a base class object (p in the example), the method needs to be declared
virtual (see 8.19).
This behavior is not unique to SystemVerilog and is similar to what you would observe in other OO languages.
If you want to have a different value for i
in LinkedPacket
, the proper way to do this would be to only declare i
in the base class, and initialize it differently in the constructor.
e.g.
class Packet;
integer i;
function new();
i = 1;
endfunction
virtual function integer get();
get = i;
endfunction
endclass
class LinkedPacket extends Packet;
function new();
i = 2;
endfunction
virtual function integer get();
get = -i;
endfunction
endclass