持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第14天!
- 在分配内存方面,仿真器对结构体和类是不同的。 结构体一声明就分配内存,类并不是这样子的。对于类,用户需要调用类的new()构造函数来为对象显示分配内存。
参考代码如下:
class rectangle;
int length;
int width;
function new (int l ,int w);
length = l;
width = w;
endfunction
function int area();
return length*width;
endfunction
endclass
module test;
rectangle u_rectangele;
initial begin
u_rectangele = new(.l(10),.w(8));
$display("u_rectangele area is %0d",u_rectangele.area());
end
endmodule
第一次我是把module模块放在class声明语句代码的上面; 也就是下面这个情况:
module test;
rectangle u_rectangele;
initial begin
u_rectangele = new(.l(10),.w(8));
$display("u_rectangele area is %0d",u_rectangele.area());
end
endmodule
class rectangle;
int length;
int width;
function new (int l ,int w);
length = l;
width = w;
endfunction
function int area();
return length*width;
endfunction
endclass
发现在命令行输入vcs -R -full64 -sverilog test.sv 会报下面这样的错误。
这报错的原因是u_rectangle 未声明。后来我才发现是因为class类的声明代码我给放下面的原因。放在上面去运行发现可以
创建对象的代码也可以简化:
u_rectangele = new(10,8);
直接这样运行也是没毛病的,毕竟class也就是一个软件的概念。
在很多情况下,特别是在验证平台的设计里。全局的数据结构还是很有用的。比如,你会在一个地方为DUT输入数据,然后在其他地方读取结果。你可能会想着把这两部分都存到一个全局的位置然后再用一个另外的自检工具来检查结果。这就是全局变量的合理用法。
我们需要的是易用易维护的全局存储的用法。OOP通过类定义中的静态变量和静态方法提供了这种功能。这简化了全局变量和方法的定义,使用和维护。