Chpater 20 Class Hierarchies and Deep Operatrion
20.1 class hierarchies
为了避免到处copy代码,和提高代码重用率,我们通过类继承(extends component)、共用对象句柄(uvm_put_port)实现。
我们重新通过Lion的例子帮助理解deep operation:
假设我们目前的class层次结构如下:
- 层次结构从最通用的animal到最特别的circus_lion,每个类都增加了有一个bit的信息,如果我们需要一个circus_lion的全部信息的话,就会出现一些挑战。
- 假设每个class都有用名为convert2string()的函数,用于将各自的单bit信息转成string类型数据以便输出:
首先,在最顶层的animal中:
virtual function string convert2string();
return $sformatf("Age: %0d", age); //只有一个变量Age
endfunction : convert2string
然后,我们在lion class中增加了性别信息:
virtual function string convert2string();
string gender_s;
gender_s = is_female ? "Female":"Male"; //我们在lion中将单bit的is_female信息转换成字符串,看起来不错
return $sformatf("Age: %0d Gender: %s", age, gender_s); //增加变量is_female
endfunction : convert2string
其次,我们在captive lion class中增加name变量:
virtual function string convert2string();
return $sformatf("Age: %0d is_female: %0d name: %s", age, is_female, name); //增加变量name
//哎呀,在lion中声明过的is_female -> string的功能,不能继承了,难受
endfunction : convert2string
如果我们希望在captive lion中也使用字符串显示性别的话,就需要从lion中将代码拷贝至代码captive lion中,但是这样每次拷贝代码,就会增加引入bug的可能性,也会导致代码难以维护。试想,如果我们的class 层次结构发生变化,如下:
我们在animal和lion之间增加了mammal,增且增加了变量babies_in_litter。同时,在mammal中定义conver2string()函数如下:
virtual function string convert2string(