1、原题
class class_a; virtual function void print_name(); $display("this is class_a"); endfunction endclass class class_b extends class_a; virtual function void print_name(); $display("this is class_b"); endfunction endclass module test; initial begin begin:class_test1 class_a a; class_b b; a = new(); b = new(); a.print_name(); b.print_name(); end begin:class_test2 class_a a; class_b b; b = new; a = b; a.print_name(); b.print_name(); end begin:class_test3 class_a a; class_a a2; class_b b; class_b b2; b = new(); a = b; a2 = new(); b2 = b; a2.print_name(); $cast(a2,a); a2.print_name(); b2.print_name(); end end endmodule
2、执行结果
1)使用a=new会创建一个新对象,并且将句柄a指向这个新创建的对象;使用a=b不会创建新对象,只是将句柄a指向已经存在的对象b
2)原因:基类中display()为虚函数,具体调用哪个x.dispaly()取决于句柄x所指向的对象类型,而不是取决于x这个句柄本身的类型
# this is class_a
# this is class_b
# this is class_b
# this is class_b
# this is class_a
# this is class_b
# this is class_b
3)原因:同2
# this is class_a
# this is class_b
# this is class_b
# this is class_b
# this is class_a
# this is class_b
# this is class_b
4)原因:基类中display()不为虚函数,具体调用哪个x.dispaly()取决于x这个句柄本身的类型
# this is class_a
# this is class_b
# this is class_a
# this is class_b
# this is class_a
# this is class_a
# this is class_b