理解System Verilog中local的和protect变量

这篇博客探讨了SystemVerilog中local和protected变量的基本定义和使用。local变量仅限于类内部使用,不允许子类和外部代码访问;而protected变量允许子类访问,但外部代码仍无法操作。通过示例代码和仿真结果,展示了当尝试非法访问这些变量时的错误情况,强调了这两个关键字在类继承和封装中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

理解System Verilog中local的和protect变量

基本定义

都是定义在类中,用来做内部变量使用的。
local和protected的区别
(1)local就是本地变量,那么在子类中就不能调用,外部不可调用。
(2)protected就是保护变量,子类可以调用操作,但是外部代码仍然不能操作该变量。
具体看如下实例,修改自路桑课件上的coding。

代码演示与结果仿真

这是将错误注释掉的,可以将注释去掉,观察仿真器的报错。如下都进行了展示。

module class_stu();
class cat;
    protected string color;
    local bit is_good;
	function set_good(bit s);
        this.is_good = s;
    endfunction
endclass
 
//声明黑猫类/
class black_cat extends cat;
    function new();
        this.color = "BLACK";
		//this.is_good = 0;	
    endfunction
	function display();
		$display("black_cat color is %s",this.color);
	endfunction
endclass
 
//声明白猫类/
class white_cat extends cat;
    function new();
        this.color = "WHITE";
		//$display("white_cat color is %s ,this cat is good %0d",this.color,this.is_good);//对于local变量,在子类的访问也是非法的
    endfunction
	function display();
		//$display("white_cat color is %s ,this cat is good %0d",this.color,this.is_good);
		$display("white_cat color is %s",this.color);
	endfunction
endclass

initial begin
	black_cat bk;    
	white_cat wt;  
    bk = new();    //初始化黑猫对象
    wt = new();    //初始化白猫对象
	//$display("black_cat color is %s",bk.color);//对于protect变量外部的访问,是不允许的
	//bk.color="red";//对于protect变量的操作,属于外部调用,会报错
	bk.display;
	wt.display;
end
endmodule

在这里插入图片描述
删除注释后的报错。错误提示是对于local以及protect变量的不正确访问。
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值