是否可以通过在 systemverilog 中使用 $cast 从基础 class 访问派生的 class 的方法?
Is it possible to access a derived class's method from a base class by using $cast in systemverilog?
我试图掌握 SystemVerilog 中的转换概念,并一直在修改以下代码:
class packet;
virtual function int compute_crc();
compute_crc = 12345;
endfunction
virtual task print;
$display("This is a packet");
endtask
endclass: packet
class bad_packet extends packet;
function int compute_crc();
compute_crc = 54321;
endfunction
task print;
$display("This is a bad packet");
endtask
task print2;
$display("This is not accessible from base");
endtask
endclass: bad_packet
module test;
packet pkt;
bad_packet b_pkt;
initial begin
b_pkt = new();
pkt = b_pkt;
$cast(b_pkt, pkt);
b_pkt.print;
pkt.print;
end
endmodule
我有一个基数 class 'packet' 和一个派生的 class 'bad_packet'。通过使用 $cast,我可以访问 bad_packet 的方法 print2 吗?还有其他方法吗?谢谢!
是的,使用 $cast 是访问基 class 中不作为虚拟方法存在的所有方法的典型方法。想一想——如果你知道你想调用只存在于扩展 class 中的东西,你需要知道那个扩展 class 的类型,所以你总是能够声明一个 class 该类型的变量并 $cast 到它。
还有一种间接调用扩展class中的非虚方法的方法,但它仍然涉及调用基class中的虚方法。您调用一个虚拟方法,让您进入扩展 class,该方法可以调用扩展 class 对象中的任何内容。这就是 clone()/copy() 方法在许多方法中所做的事情。
我试图掌握 SystemVerilog 中的转换概念,并一直在修改以下代码:
class packet;
virtual function int compute_crc();
compute_crc = 12345;
endfunction
virtual task print;
$display("This is a packet");
endtask
endclass: packet
class bad_packet extends packet;
function int compute_crc();
compute_crc = 54321;
endfunction
task print;
$display("This is a bad packet");
endtask
task print2;
$display("This is not accessible from base");
endtask
endclass: bad_packet
module test;
packet pkt;
bad_packet b_pkt;
initial begin
b_pkt = new();
pkt = b_pkt;
$cast(b_pkt, pkt);
b_pkt.print;
pkt.print;
end
endmodule
我有一个基数 class 'packet' 和一个派生的 class 'bad_packet'。通过使用 $cast,我可以访问 bad_packet 的方法 print2 吗?还有其他方法吗?谢谢!
是的,使用 $cast 是访问基 class 中不作为虚拟方法存在的所有方法的典型方法。想一想——如果你知道你想调用只存在于扩展 class 中的东西,你需要知道那个扩展 class 的类型,所以你总是能够声明一个 class 该类型的变量并 $cast 到它。
还有一种间接调用扩展class中的非虚方法的方法,但它仍然涉及调用基class中的虚方法。您调用一个虚拟方法,让您进入扩展 class,该方法可以调用扩展 class 对象中的任何内容。这就是 clone()/copy() 方法在许多方法中所做的事情。