virtual
SV不允许一个子类句柄指向父类对象,但是可以让一个父类句柄指向子类对象。由于父类句柄只能访问父类的成员变量和方法,不利于验证环境的复用;所以为了让继承了同一父类的子类能将一个同名方法扩展为不同功能的方法,利用类的多态,将父类中的方法声明为virtual,而指向子类对象的句柄就可以根据指向的对象类型,而不是句柄类型来调用我们希望调用的方法。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class father; function display(); $display("This is Father!!); endfunction endclass class son extends father; function display(); $display("This is Son!!"); endfunction endclass module tb; father father_inst; son son_inst; intial begin son_inst = new(); father_inst = son_inst; //父类句柄指向子类对象 father_inst.display(); son_inst.display(); end endmoduleView Code
结果
This is Father!!
This is Son!!
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class father; virtual function display(); $display("This is Father!!); endfunction endclass class son extends father; virtual function display(); $display("This is Son!!"); endfunction endclass module tb; father father_inst; son son_inst; intial begin son_inst = new(); father_inst = son_inst; father_inst.display(); son_inst.display(); end endmoduleView Code
结果
This is Son!!
This is Son!!
从上述两个代码中发现:
1)不使用virtual,父类句柄虽指向子类对象,但调用的仍是父类本身的函数
2)使用virtual,父类句柄指向子类对象,调用的是子类的函数
类似上述总结结论:
1)声明虚方法时,根据对象来决定调用
2)未声明虚方法时,根据句柄来决定调用
cast
father_inst = new();
son_inst = father_inst; //子类直接指向父类(编译报错)
$cast(son_inst,father_inst); //直接使用cast向下转换(编译报错)
正确方式
son son1,son2; father father_inst; son1 = new(); father_inst = son1; $cast(son2,father_inst);
标签:句柄,father,SV,virtual,son,cast,inst,父类,display From: https://www.cnblogs.com/Dukefish/p/17096919.html