oop - How can one access a base class method using base class object once it has been overwritten?
问题描述
This question might be applicable to all/most Object-oriented programming languages but I am only concerned about the SystemVerilog side. Polymorphism, I thought I understood, until I was talking to a colleague the other day and this came and I realised that I don't know how this can be done. Following are the two classes to consider for the purpose of this discussion -
class four_wheeler;
virtual function void vehicle_type();
$display("Four-wheeler");
endfunction:vehicle_type
virtual task colour();
$display("Many colours");
endtask:colour
endclass:four_wheeler
class jaguar extends four_wheeler;
function void vehicle_type();
$display("Jaguar");
endfunction:vehicle_type
task colour();
$display("Black");
endtask:colour
endclass:jaguar
program sv_prog;
initial begin
four_wheeler four_wheeler_h;
jaguar jaguar_h;
four_wheeler_h = new();
jaguar_h = new();
four_wheeler_h = jaguar_h;
four_wheeler_h.vehicle_type();
end
endprogram: sv_prog
I want to access the vehicle_type()
function in the base class four_wheeler using its own object. I can do this by four_wheeler_h.vehicle_type()
before the four_wheeler_h = jaguar_h
copy. Regular OOP working! But can I do it after the copy of the handle?
I can use the super
keyword in jaguar class vehicle_type()
method:
function void vehicle_type();
super.vehicle_type();
$display("Jaguar");
endfunction:vehicle_type
and get the output:
Four-wheeler
Jaguar
But I am more interested in doing this from the program block itself without having to modify the function in the jaguar class. Is there any way I can achieve that? Maybe a use of super
from the program block itself.
解决方案
我担心与 c++ 不同,您的操作方式非常有限(就像在 java 中一样)。所以,所有的语言都是不同的。
与 java 类似,SystemVerilog 为您提供了可以在类成员中使用的关键字“super”。您将必须创建一个特定的类成员函数以在非类范围内访问其基(超)类成员:
class jaguar extends four_wheeler;
...
function super_vehicle_type();
super.vehicle_type();
endfunction
endclass:jaguar
现在你可以使用
jaguar_h.super_vehicle_type();
您还可以在函数中使用类范围标识符来访问任何基类。
function super_vehicle_type();
four_wheeler::vehicle_type();
endfunction
在上述情况下,您可以使用任何基类(而不是four_wheeler)作为类范围。
推荐阅读
- sql - BigQuery - 创建视图时如何使用嵌套列更改架构的顺序?
- flutter - 为什么我的 AppBar 标题会更改缩进?
- php - php 返回 '?' 尽管它们已正确保存在 mysql 中,但仍以正方形而不是特殊字符
- php - Doctrine 固定装置加载,有问题设置引用(外键)违反 -not-null 约束
- python - 如何在熊猫数据框中添加具有重复值的列?
- php - 使用 PhpSpreadsheet 在单元格中插入 HTML 代码
- python - “utf-8-sig”是否适合解码 UTF-8 和 UTF-8 BOM?
- r - 用列表和数据框聚合,函数如何知道聚合级别?
- tomcat8 - AWS ALB 很多 504 响应代码
- javascript - 设置新状态不会使用 React Hooks 重新渲染组件