当前位置:网站首页>SV 类的虚方法 多态
SV 类的虚方法 多态
2022-08-05 00:13:00 【Bunny9__】
SV 类的虚方法 多态 类型转换
概述
- 类的成员方法可以加修饰词
virtual(虚方法) - 虚方法是一种基本的多态结构
- 一个虚方法可以覆盖基类的同名方法
- 在父类和子类中声明虚方法,其方法名、参数名、参数方向都应该保持一致
- 在调用虚方法时,它将调用句柄指向对象的方法,而不受句柄类型的影响
class BasePacket;
int A = 1;
int B = 2;
function void printA;
$display("BasePacket::A is %d", A);
endfunction
virtual function void printB;
$display("BasePacket::B is %d", B);
endfunction
endclass
class My_Packet extends BasePacket;
int A = 3;
int B = 4;
function void printA;
$display("My_Packet::A is %d", A);
endfunction
virtual function void printB;
$display("My_Packet::B is %d", B);
endfunction
endclass
module tb;
BasePacket P1 = new();
My_Packet P2 = new();
initial begin
P1.printA; // A is 1
P1.printB; // B is 2
P1 = P2; // 子类句柄赋值给父类,父类句柄指向子类的对象
P1.printA; // A is 1
P1.printB; // B is 4
P2.printA; // A is 3
P2.printB; // B is 4
end
endmodule


父类句柄默认会查找调用父类方法,当子类句柄赋值给父类,父类句柄指向子类的对象后,父类句柄查找方法会扩大到子类里,如果子类里有同名方法,那么就会执行子类的同名方法。故P1.printB()和P2.printB()打印结果都是4。
virtual关键字的作用:虽然句柄类型不一样,但是调用函数会以子类的实现优先,即子类如果有同名方法就调用子类里的方法。
变量能不能也声明成virtual:不可以
- 人家都叫虚方法了,都没说虚变量诶
- 父类访问方法的范围可以扩展到子类,但是访问的变量范围只有父类变量范围
- 上述代码子类方法可以不用virtual声明,但是父类一定要声明
- 上述代码,父类不用virtual,子类用virtual,则不行,这样父类对象在查找方法时候,不知道要去子类找,只会在父类范围内查找
一些建议点:
- 类在封装的时候建议不要local、protected
- 类在继承的时候,为了方便以后访问到更多的变量,子类继承父类的时候尽量不要出现同名变量
边栏推荐
猜你喜欢

子连接中的参数传递

How to burn the KT148A voice chip into the chip through the serial port and the tools on the computer

MAUI Blazor 权限经验分享 (定位,使用相机)

golang 协程的实现原理

KT148A voice chip ic working principle and internal architecture description of the chip

Nuclei (2) Advanced - In-depth understanding of workflows, Matchers and Extractors

翁恺C语言程序设计网课笔记合集

元宇宙:未来我们的每一个日常行为是否都能成为赚钱工具?

三、实战---爬取百度指定词条所对应的结果页面(一个简单的页面采集器)

没有这些「伪需求」,产品经理的 KPI 怎么完成?
随机推荐
子连接中的参数传递
oracle创建表空间
如何写好测试用例
【数据挖掘概论】数据挖掘的简单描述
数据类型及输入输出初探(C语言)
Modelers experience sharing: model study method
LeetCode Hot 100
what is MVCC
KT6368A Bluetooth certification problem_FCC and BQB_CE_KC certification or other instructions
MongoDB权限验证开启与mongoose数据库配置
KT6368A蓝牙的认证问题_FCC和BQB_CE_KC认证或者其它说明
STC89C52RC的P4口的应用问题
.net (C#) get year month day between two dates
阅读笔记:如何理解DevOps?
Day118. Shangyitong: order list, details, payment
刘润直播预告 | 顶级高手,如何创造财富
【无标题】线程三连鞭之“线程池”
网站最终产品页使用单一入口还是多入口?
三大技巧让你成功入门3D建模,零基础小白必看
Develop a SpaceX website based on the Appian low-code platform