1

下面代码中的对象只被实例化了一次,对吧?所以已经实例化的单个对象应该包含一个值为 2 的整数 i 字段。为什么p.i给出 1 而不是 2?这是 SystemVerilog 特有的吗?还是所有 oop 语言的行为都相似?

class Packet; 
  integer i = 1;
  function integer get();
    get = i;
  endfunction 
endclass

class LinkedPacket extends Packet;
  integer i = 2;
  function integer get();
    get = -i;
  endfunction 
endclass

LinkedPacket lp = new;
Packet p = lp;
j = p.i; // j = 1, not 2
j = p.get(); // j = 1, not -1 or –2 

谢谢

4

2 回答 2

3

此示例粘贴自 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
于 2012-07-24T14:36:02.163 回答
0

我不是 SystemVerilog 专家,但我希望p.i返回1,因为这就是你初始化它的目的。 p.get()只是返回相同值的另一种方式,所以也将是1.

j=get();将(我认为)返回-2- 没有对象前缀,我希望它调用类之外的第二个函数。

于 2012-07-24T13:03:54.813 回答