SystemVerilog中的类构造函数new

嵌入式技术

1332人已加入

描述

基类构造函数

在systemverilog中,如果一个类没有显式地声明构造函数(new()),那么编译仿真工具会自动提供一个隐式的new()函数。这个new函数会默认地将所有属性变量。
初始化为默认值(“0”:2状态变量,“x”:4状态变量)。

super.new( )

继承类中new()函数默认一开始就会调用其父类中的new()函数(super.new( )).

 

 module class_TOP( );
 
 class base;
 function new( );
 $display($stime,,," new( ) from BASE Class");
 endfunction
 endclass : base
 
 class ext extends base;
 function new;
 super.new( ); //MUST be the frst statement
 $display($stime,,, "Call super.new from Extended 
class");
 endfunction
 endclass: ext
 
 base base1;
 ext ext1;
 
 initial begin;
 ext1 = new( );
 end
 
 initial #1 $fnish(2);
 endmodule

 

仿真log:

 

0 new( ) from BASE Class
0 Call super.new from Extended class
$fnish at simulation time 1
 V C S S i m u l a t i o n R e p o r t

 

上面是一个关于继承类构造函数执行顺序的简单示例。在类“base”中,我们定义了它的构造函数new(),一个简单的$display语句。

然后我们将“base”类扩展到“ext”类。当"ext"被实例化时,它的new()方法将首先调用super.new ()。

在仿真log中,我们看到" base "类的display语句比"ext"类的display语句先执行。

另外还需要知道的是,如果你去掉“super.new”,我们依然会得到相同的仿真打印信息,因为编译仿真工具会默认帮我们添加“super.new”语句。

但是,如果new函数中存在参数,就必须要要显式地加上super.new (*),因为工具事先没法知道你想要声明的参数是什么?

强烈建议在所有的扩展类中都显式地加上super.new ,以获得更好的可读性。

 

module class_TOP( );
 
 class base;
 logic [31:0] data;
 function new(logic [31:0] dataIn);
 data = dataIn;
 $display($stime,,, "new( ) from BASE Class: data=%h",
 data);
 endfunction
 endclass : base
 
 class ext extends base;
 function new (logic [31:0] dataExt);
 super.new(dataExt); //MUST call super.new
 //MUST be the frst statement
 //pass dataExt to the base class constructor
 $display($stime,,, "super.new from Extended class");
 endfunction
 endclass: ext
 
 base base1;
 ext ext1;
 logic [31:0] data;
 initial begin;
 data = 'hf0f0_f0f0;
 ext1 = new(data);
 end
 initial #10 $fnish(2);
 
 endmodule

 

仿真log:

 

0 new( ) from BASE Class: data=f0f0f0f0
0 super.new from Extended class
$fnish at simulation time 10
 V C S S i m u l a t i o n R e p o r t

 

在本例中,我们在new函数中传递参数dada,以初始化类中的变量。如果这时我们不加上super.new,仿真工具就会报错:

 

Error-[SV-SNCIM] Super new call is missing
testbench.sv, 13
class_TOP
Base class constructor specifcation is missing in derived class 'ext'.
Please add ::new arguments to 'extends' specifcation or add
call to 'super.new' in ::new.

 

  审核编辑:汤梓红

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分