2010-11-11 08:40:11| 分类: SystemVerilog | 标签: |举报 |字号大中小 订阅
今天翻译了一个重要概念:类的继承
来源:http://systemverilog.co/wiki/Class_Inheritance
继承是面向对象编程范式的关键概念。类用来创建用户自定义类型. 继承使得用户可以用非常安全,非侵入的方式对类的行为进行增加或者修改。使用继承可以定义子类型,在子类型中增加新的方法和数据。被继承的类一般称为基类(SystemVerilog中的超类),得到的新类一般称为引申类(或子类)。
为什么继承如此重要? 因为它使得复用得以实现。让我们通过实例来说明. 假设我们对一个图像模块进行建模. 对其中一部分,我们写了一个代表颜色的类:
class Color;
byte unsigned red;
byte unsigned green;
byte unsigned blue;
function new(byte unsigned red_ = 255,
byte unsigned green_ = 255,
byte unsigned blue_ = 255);
red = red_;
green = green_;
blue = blue_;
endfunction: new
function mix(Color other);
function brighter(float percent);
task draw_pixel(int x, int y);
class Color;
byte unsigned red;
byte unsigned green;
byte unsigned blue;
byte unsigned alpha;
function new(byte unsigned red_ = 255,
byte unsigned green_ = 255,
byte unsigned blue_ = 255,
byte unsigned alpha_ = 255);
red = red_;
green = green_;
blue = blue_;
alpha = alpha_;
endfunction: new
function mix(Color other); // new implementation -- would depend on
// alpha values for both the colors
function brighter(float percent); // original implementation good enough
task draw_pixel(int x, int y); // new implementation
// Other functions ...
endclass: Color
class ColorWithAlpha extends Color;
byte unsigned alpha;
function new(byte unsigned red_ = 255,
byte unsigned green_ = 255,
byte unsigned blue_ = 255,
byte unsigned alpha_ = 255);
super.new(red_, green_, blue_);
alpha = alpha_;
endfunction: new
function mix(Color other); // new implementation -- would depend on
// alpha values for both the colors
task draw_pixel(int x, int y); // new implementation
// Other functions ...
endclass: Color
这里我们使用关键字"extend" 来创建一个新类ColorWithAlpha. 注意到我们仅仅需要声明新增加的alpha数据成员。其他成员作为超类对象的一部分用来表示原始的Color类。
有C++背景的用户会注意到在如何访问原始Color类成员的方式,SystemVerilog和C++很不一样。在C++中,原始类(基类)的数据成员的就像本来也就属于继承类的成员一样;在SystemVerilog中,需要额外一层的间接访问,super指定的超类对象和继承类被看作不同的对象。但是,如果需要在继承类中去访问基类成员,SystemVerilog编译器会隐式的帮助完成这部分间接访问。(译者补充:不需要用super去限定,编译器帮忙做这个事情)
ColorWithAlpha color1;
color1 = new(127, 127, 127, 255); // solid gray50
color1.brighter(50); // make 50% brighter
if (color1.red == 127) begin
// some code
// ..
end
Dr Bertrand Meyer 由于发明了“开-关”定律而享有盛誉。 此定律被认为是面向对象编程中最重要的原则。简而言之,此定律告诉我们写模块的时候应该使得模块在不做修改的情况下很容易扩展。此定律更正式的表述如下[2]:
软件单元(类,模块,函数,等等)应该对扩展开放,但是对修改关闭。
评论