当前位置:网站首页>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
- 类在继承的时候,为了方便以后访问到更多的变量,子类继承父类的时候尽量不要出现同名变量
边栏推荐
- Senior game modelers tell newbies, what are the necessary software for game scene modelers?
- 三、实战---爬取百度指定词条所对应的结果页面(一个简单的页面采集器)
- 关于我仔细检查审核过关于工作人员页面,返回一个所属行业问题
- 关于使用read table 语句
- uinty lua 关于异步函数的终极思想
- 矩阵数学原理
- 10 个关于 Promise 和 setTimeout 知识的面试题,通过图解一次说透彻
- #yyds干货盘点#交换设备丢包严重的故障处理
- The role of the annotation @ EnableAutoConfiguration and how to use
- How to burn the KT148A voice chip into the chip through the serial port and the tools on the computer
猜你喜欢
随机推荐
Basic web in PLSQL
lua 如何 实现一个unity协程的工具
10 个关于 Promise 和 setTimeout 知识的面试题,通过图解一次说透彻
MongoDB permission verification is turned on and mongoose database configuration
在线中文姓名生成工具推荐
看图识字,DELL SC4020 / SCv2000 控制器更换过程
【Unity编译器扩展之进度条】
leetcode经典例题——单词拆分
4 - "PyTorch Deep Learning Practice" - Backpropagation
机器学习(公式推导与代码实现)--sklearn机器学习库
Metasploit-域名上线隐藏IP
Mysql_14 存储引擎
三大技巧让你成功入门3D建模,零基础小白必看
阅读笔记:如何理解DevOps?
【无标题】线程三连鞭之“线程池”
The role of the annotation @ EnableAutoConfiguration and how to use
[Happy Qixi Festival] How does Nacos realize the service registration function?
论文解读( AF-GCL)《Augmentation-Free Graph Contrastive Learning with Performance Guarantee》
Mysql_13 事务
what is MVCC









