前言
今天和某大佬交流了下System Verilog中的OOP属性,本来自己对这块一直感觉还比较良好,但是跟大佬交流后才发现原来要学的还有很多。
拓展类的构造函数
具体内容可以参考"IEEE system verilog标准" 8.7 "constructors"/8.8 "typed constructor calls"以及绿皮书8.1.4节"拓展类的构造函数"。
要点1:无论是否super.new,子类new都会自动调用父类的new;
class father;
int flow_id;
function new(int id = 100);
$display("new father");
flow_id = id;
endfunction: new
endclass: father
class son extends father;
function new();
$display("new son, flow_id='d%0d", flow_id);
endfunction: new
endclass: son
//env
...
begin
father obj_fa1;
father obj_fa2;
son obj_sn1;
son obj_sn2;
obj_fa1 = new(15);
obj_sn1 = new();
end
...
打印结果如下:
当然了如果不调用super.new的话,就无法改变传参值。
要点1:如果父类new有且必须传参,子类new必须调用super.new并且进行传参;
如果将上述代码father类呢new修改为如下形式,编译时会报错。
class father;
int flow_id;
function new(int id);
$display("new father");
flow_id = id;
endfunction: new
endclass: father
class son extends father;
function new();
$display("new son, flow_id='d%0d", flow_id);
endfunction: new
endclass: son
//env
...
begin
father obj_fa1;
father obj_fa2;
son obj_sn1;
son obj_sn2;
obj_fa1 = new(15);
obj_sn1 = new();
end
...
报错如下:
要点3:父类句柄可以直接构造子类对象,反之则会报错;
class father;
int flow_id;
function new(int id);
$display("new father");
flow_id = id;
endfunction: new
endclass: father
class son extends father;
function new();
super.new(30);
$display("new son, flow_id='d%0d", flow_id);
endfunction: new
endclass: son
//env
...
begin
father obj_fa1;
father obj_fa2;
son obj_sn1;
son obj_sn2;
obj_fa2 = son::new();
obj_sn2 = father::new(40);
end
...
编译时未报错,但是在run时会报错如下:
该报错实际与子类句柄指向父类实例的error是一致的,都会被禁止。
如果想到其他的再来补充。。。