从子类内部使用super关键字来引用基类的属性和方法。 如果子类已覆盖属性和方法,则必须使用super关键字来访问它们。
例
super关键字只能在从基类派生的类范围内使用。 由于extPacket不是Packet的子代,因此下面显示的代码将具有编译错误。 注意,为每个类定义隐式定义了新方法,因此在基类Packet中不需要新的定义。
class Packet;
int addr;
function display ();
$display ("[Base] addr=0x%0h", addr);
endfunction
endclass
class extPacket; // 缺少“extends”关键字->不是子类
function new ();
super.new ();
endfunction
endclass
module tb;
Packet p;
extPacket ep;
initial begin
ep = new();
p = new();
p.display();
end
endmodule
Simulation Log
super.new ();
|
ncvlog: *E,CLSSPX (testbench.sv,12|8): 'super' can only be used within a class scope that derives from a base class.
现在让我们看一下extPacket是Packet类的派生类时的输出。
访问基类方法
在下面显示的示例中,使用super关键字从子类的显示方法中调用基类的显示方法。
class Packet;
int addr;
function display ();
$display ("[Base] addr=0x%0h", addr);
endfunction
endclass
class extPacket extends Packet;
function display();
super.display(); // 调用基类的显示方法
$display ("[Child] addr=0x%0h", addr);
endfunction
function new ();
super.new ();
endfunction
endclass
module tb;
Packet p;
extPacket ep;
initial begin
ep = new();
p = new();
ep.display();
end
endmodule
Simulation Log
ncsim> run
[Base] addr=0x0
[Child] addr=0x0
ncsim: *W,RNQUIE: Simulation is complete.
参考文献:
【1】https://editor.csdn.net/md?articleId=104484693