为什么在systemverilog中继承常量变量无效



以下代码有什么问题。

program test;
class a;
const int i;
endclass : a
class b extends a;
function new();
i = 10;
endfunction : new
endclass : b
class c extends a;
function new();
i = 100;
endfunction : new
endclass : c
initial begin
b bo = new();
c co = new();
$display(bo.i, co.i);
end
endprogram : test

我得到以下编译错误

实例常量的初始化无效:无法初始化"i">

构造函数中不止一次。可能会重新初始化

at语句:this.i=10;上一篇:test.sv,9来源信息:

this.i=10;

在构造类对象的过程中,只能对const变量进行一次赋值。它必须作为其声明的一部分,或者在其相应的构造函数方法期间进行赋值。尽管您没有在class a中编写显式构造函数方法,但SystemVerilog为您创建了一个隐式构造函数方法。两者都没有,因此其初始值为0。重写实例常量值的唯一方法是将其作为构造函数参数或参数化传递。

class a;
const int i;
function new(int aa = 10);
i = aa;
endfunction
endclass : a
class b extends a;
function new(int aa=100);
super.new(aa); // super.new(); is implicitly added if you don't
endfunction : new
endclass : b
class c extends b;
function new();
super.new(500); // super.new(); is implicitly added if you don't
endfunction : new
endclass : b

还要注意,当变量在过程代码中隐式声明为static变量时,现在初始化变量是非法的。您应该将它们移到开始/结束块之外,或者使用staticautomatic关键字添加显式生存期。

b bo = new();
initial begin
static c co = new();
$display(bo.i, co.i);
end

这使得声明在程序循环中有很大的不同。

最新更新