資源描述:
《system verilog 類的繼承》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫。
1、類的繼承SystemVerilog支持單繼承(類似Java,而不像C++).有一個讓SystemVerilog支持多重繼承的提案[1],但是短期內(nèi)不會看到曙光。目錄·1什么是繼承?·2有什么好處·3開-關(guān)定律·4參考資料什么是繼承?繼承是面向?qū)ο缶幊谭妒降年P(guān)鍵概念。類用來創(chuàng)建用戶自定義類型.繼承使得用戶可以用非常安全,非侵入的方式對類的行為進行增加或者修改。使用繼承可以定義子類型,在子類型中增加新的方法和數(shù)據(jù)。被繼承的類一般稱為基類(SystemVerilog中的超類),得到的新類一般稱為引申類(或子類)。為什么繼承如此重要?因為它使得復(fù)用得以實現(xiàn)。讓我們
2、通過實例來說明.假設(shè)我們對一個圖像模塊進行建模.對其中一部分,我們寫了一個代表顏色的類:classColor;byteunsignedred;byteunsignedgreen;byteunsignedblue;functionnew(byteunsignedred_=255,byteunsignedgreen_=255,byteunsignedblue_=255);red=red_;green=green_;blue=blue_;endfunction:newfunctionmix(Colorother);functionbrighter(floatpe
3、rcent);taskdraw_pixel(intx,inty);Now現(xiàn)在它的下一個版本希望能夠處理部分透明的圖像。為此,我們給Color類增加了一個alpha成員,。alpha代表圖像的透明度。alpha越大,圖像的像素越結(jié)實(不透明)。'0'代表完全透明,使得圖片的背景全部可見。因此,我們修改color類如下:classColor;byteunsignedred;byteunsignedgreen;byteunsignedblue;byteunsignedalpha;functionnew(byteunsignedred_=255,byteunsig
4、nedgreen_=255,byteunsignedblue_=255,byteunsignedalpha_=255);red=red_;green=green_;blue=blue_;alpha=alpha_;endfunction:newfunctionmix(Colorother);//newimplementation--woulddependon//alphavaluesforboththecolorsfunctionbrighter(floatpercent);//originalimplementationgoodenoughtaskdraw
5、_pixel(intx,inty);//newimplementation//Otherfunctions...endclass:Color注意,即使許多代碼是由之前版本的Color類復(fù)制而來,我們還是需要單獨維護兩個版本的代碼。這時繼承就可以發(fā)揮作用,使用繼承,我們可以簡單的從原始的Color類繼承出新類,來添加alpha成員。classColorWithAlphaextendsColor;byteunsignedalpha;functionnew(byteunsignedred_=255,byteunsignedgreen_=255,byteunsig
6、nedblue_=255,byteunsignedalpha_=255);super.new(red_,green_,blue_);alpha=alpha_;endfunction:newfunctionmix(Colorother);//newimplementation--woulddependon//alphavaluesforboththecolorstaskdraw_pixel(intx,inty);//newimplementation//Otherfunctions...endclass:Color這里我們使用關(guān)鍵字"extend"來創(chuàng)建一個
7、新類ColorWithAlpha.注意到我們僅僅需要聲明新增加的alpha數(shù)據(jù)成員。其他成員作為超類對象的一部分用來表示原始的Color類。有C++背景的用戶會注意到在如何訪問原始Color類成員的方式,SystemVerilog和C++很不一樣。在C++中,原始類(基類)的數(shù)據(jù)成員的就像本來也就屬于繼承類的成員一樣;在SystemVerilog中,需要額外一層的間接訪問,super指定的超類對象和繼承類被看作不同的對象。但是,如果需要在繼承類中去訪問基類成員,SystemVerilog編譯器會隱式的幫助完成這部分間接訪問。(譯者補充:不需要用super去
8、限定,編譯器幫忙做這個事情)ColorWithAlphacolor