SystemVerilog super 关键字:调用父类实现

super 用于在派生类中显式引用父类成员。它解决“覆盖后如何复用父类行为”的问题。

1. super.new

1
2
3
4
5
6
7
8
9
10
11
12
class base;
int x;
function new(int v); x = v; endfunction
endclass

class ext extends base;
int y;
function new(int v);
super.new(v); // 必须先调用
y = v * 2;
endfunction
endclass

派生类构造必须先完成父类构造,否则父类字段未初始化。

2. super.method

1
2
3
4
5
6
7
8
9
10
class base;
function virtual void show(); $display("base"); endfunction
endclass

class ext extends base;
function virtual void show();
super.show(); // 输出 base
$display("ext");
endfunction
endclass

super.show() 调用父类实现,this.show() 会再次分派到派生类,造成递归。

3. 常见误区

  1. 用 this 代替 super 调用父类方法:造成无限递归。
  2. 忘记 super.new:父类构造未执行。
  3. 在静态上下文中使用 super:非法。

小结

super 表达“向上调用”,this 表达“当前对象”。覆盖方法时先想清楚要复用父类哪一部分,再选择 super 还是完全重写。

参考文献:ChipVerify SystemVerilog Tutorial — SystemVerilog super Keyword 章节(https://chipverify.com/systemverilog/systemverilog-super)。本文为原创中文讲解。