类可以定义在program、module、package中或者这些块的任意地方。
类的术语
类、对象、句柄、属性、方法、原型相对应于verilog中的模块、例化模块、实例名、reg或者wire变量、initial块和task和function和always块、执行代码。
创建对象
如下例所示:
class first_class;
int data[7] = '{1,9,8,7,5,4,3};
int a[$];
function sort_fu();
.......
endfunction
endclass
initial begin
first_class data_first;
data_first = new();
data_first.sort_fu;
end
如上图所示,定义一个类 first_class,然后data_first为一个指向 first_class类型对象的一个句柄,new()为first_class分配空间将变量初始化为默认值,并返回保存对象的地址。
在类中也可以定义new()函数对类中的变量进行配置,例如
class first_class;
int data[7];
int data_2 ;
int a[$];
function sort_fu();
.......
endfunction
function new(int a = 7);
data_2 = a;
foreach(data[i])
data[i] = i;
endfunction
endclass
如上所示,对类中的变量设置定值。
静态变量和全局变量
如下所示为定义一个静态变量
class first_class;
static int count = 0;
int data[7];
int data_2 ;
int a[$];
function sort_fu();
.......
endfunction
function new(int a = 7);
count = count + 1;
data_2 = a;
foreach(data[i])
data[i] = i;
endfunction
endclass
在类中定义一个static的变量,并进行初始化,除了通过句柄去访问静态变量,可以通过类名加上::来访问静态变量。同样可以在类之外定义方法,如下所示
class first_class;
static int count = 0;
int data[7];
int data_2 ;
int a[$];
extern function sort_fu();
endclass
function first_class::sort_fu();
.......
endfunction
复制方法的第一行,包括方法名和参数,并添加关键字extern,将整个方法移至类定义后面,并在方法名前加上类名和两个冒号(::)。
作用域规则
"this"可以将局部变量赋给类变量,如下
class first_class;
int data;
function new(int data);
this.data = data;
endfunction
endclass
initial begin
first_class data_one;
data_one = new(10);
end
可以对类中的变量进行赋值,如果没有function new(int data),则data的默认值为0。
如果需要在类中再使用一个类,则需要在类中的function new()中对另外一个使用的类进行 new(),否则会出现失败。
对象的复制
使用new操作符复制一个对象,这是一种浅复制,如下所示:
class furst_b;
int a;
function dis();
$display ("the number is %d",a);
endfunction
endclass
class first_a;
int a_data;
int aa_data;
furst_b a_class; //使用另外一个类
function new;
a_class = new();
endfunction
endclass
initial begin
first_a cla_first, cla_second;
cla_first = new();
cla_first.a_class.a = 12;
cla_first.a_class.dis(); //显示12
cla_second = new cla_first;
cla_second.a_class.a = 24;
cla_first.a_class.dis(); //显示24
end
如上述代码所示,其中new操作符对类进行复制,但这种复制只是对类中的对象进行复制,没有对类中的下层对象进行复制,因此在代码中,如果对类中下层对象进行修改,则会对两个类都有影响,因此当第二个类对类中下层对象进行修改,第一个类的下层对象也会修改。
如果想实现深层复制,则需要编写复制函数copy,如下所示:
program data_test;
class furst_b;
int a;
function dis();
$display ("the number is %d",a);
endfunction
function furst_b copy;
copy = new();
copy.a = a;
endfunction
endclass
class first_a;
int a_data;
int aa_data;
furst_b a_class;
function first_a copy;
copy = new();
copy.a_data = a_data;
copy.aa_data = aa_data;
copy.a_class = a_class.copy();
endfunction
function new;
a_class = new();
endfunction
endclass
initial begin
first_a cla_first, cla_second;
cla_first = new();
cla_first.a_class.a = 12;
cla_first.a_class.dis(); //显示12
cla_second = cla_first.copy();
cla_second.a_class.a = 24;
cla_first.a_class.dis(); //显示12
cla_second.a_class.dis(); //显示24
end
如上则完成类的深层复制,其中function copy中调用了构造函数new,则需要在调用的下层类中也增加一个类似的copy函数,如furst_b中的copy所示,则copy函数完成类的深复制。