声明为local的变量仅可用于同一类的方法,并且子类无法访问。 但是,访问本地成员的非本地方法可以由子类继承和覆盖。
例
在下面的示例中,我们将声明两个变量-一个公共变量和另一个局部变量。 当从类外部的某个地方访问该类的本地成员时,我们期望看到一个错误。 这是因为关键字local用于使成员保持本地状态,并且仅在同一类中可见。
当从类外部访问时
class ABC;
// 默认情况下,所有变量都是公共变量,对于此示例,
// 让我们创建两个变量-一个公共变量,另一个“本地变量”
byte public_var;
local byte local_var;
// 此功能仅打印这些变量内容
function void display();
$display ("public_var=0x%0h, local_var=0x%0h", public_var, local_var);
endfunction
endclass
module tb;
initial begin
// 创建一个新的类对象,并调用display方法
ABC abc = new();
abc.display();
//可以通过类句柄访问公共变量
$display ("public_var = 0x%0h", abc.public_var);
// 但是,局部变量不能从外部访问
$display ("local_var = 0x%0h", abc.local_var);
end
endmodule
不出所料,编译器会发出编译错误,该错误指向从类外部访问本地成员的行。
$display ("local_var = 0x%0h", abc.local_var);
|
ncvlog: *E,CLSNLO (testbench.sv,24|47): Access to local member 'local_var' in class 'ABC' is not allowed here.
irun: *E,VLGERR: An error occurred during parsing. Review the log file for errors with the code *E and fix those identified problems to proceed. Exiting with code (status 1).
在上面的示例中,我们可以删除导致编译错误的行,并看到输出良好。 访问本地成员的唯一其他函数是display()函数。
module tb;
initial begin
ABC abc = new();
// This should be able to print local members of class ABC because display() is a member of ABC also
abc.display();
// Public variables can always be accessed via the class handle
$display ("public_var = 0x%0h", abc.public_var);
end
endmodule
Simulation Log
ncsim> run
public_var=0x0, local_var=0x0
public_var = 0x0
ncsim: *W,RNQUIE: Simulation is complete.
子类访问
在此示例中,让我们尝试从子类中访问本地成员。我们也希望在这里看到一个错误,因为子类也不可见。
// Define a base class and let the variable be "local" to this class
class ABC;
local byte local_var;
endclass
// Define another class that extends ABC and have a function that tries to access the local variable in ABC
// 定义另一个扩展ABC并具有试图访问ABC中的局部变量的函数的类
class DEF extends ABC;
function show();
$display ("local_var = 0x%0h", local_var);
endfunction
endclass
module tb;
initial begin
// 创建子类的新对象,并调用show方法
// 这将产生一个编译时错误,因为子类无法访问基类的“局部”变量和方法
DEF def = new();
def.show();
end
endmodule
参考文献:
【1】https://www.chipverify.com/systemverilog/systemverilog-local-access-level