背景
H为基类,R,G,B为子类,分别继承自H基类。
class H;
virtual function void f();
$display("Calling f() in H");
endfunction
endclass
class R extends H;
function void f();
$display("Calling f() in R");
endfunction
endclass
class G extends H;
function void f();
$display("Calling f() in G");
endfunction
endclass
class B extends H;
function void f();
$display("Calling f() in B");
endfunction
endclass
多态-dynamic cast
归一化公共处理组件,在编写公共组件时,无需考虑子类的具体行为,只需要按照基类提供的统一接口处理即可。
如下面的process_common函数,其输入和输出均是基类类型。
但当归一化处理完毕后,各个子类接收后,需要个性化处理时,做一次dynamic cast将基类cast到子类即可。
class H;
virtual function void f();
$display("Calling f() in H");
endfunction
endclass
class R extends H;
function void f();
$display("Calling f() in R");
endfunction
function void g();
$display("Calling g() in R");
endfunction
endclass
class G extends H;
function void f();
$display("Calling f() in G");
endfunction
function void g();
$display("Calling g() in G");
endfunction
endclass
class B extends H;
function void f();
$display("Calling f() in B");
endfunction
function void g();
$display("Calling g() in B");
endfunction
endclass
function automatic H process_common(input H input_obj);
H output_obj;
input_obj.f();
output_obj = input_obj;
return output_obj;
endfunction
module top;
R R_PTR;
G G_PTR;
B B_PTR;
H H0_PTR;
H H1_PTR;
H H2_PTR;
initial begin
H h = new();
R r = new();
G g = new();
B b = new();
// 调用 process_common 函数并打印输出
H0_PTR = process_common(r);
$cast(R_PTR, H0_PTR);
$display("Output from process_common with R input:");
R_PTR.g();
H1_PTR = process_common(r);
$cast(G_PTR, H1_PTR);
$display("Output from process_common with G input:");
G_PTR.g();
H2_PTR = process_common(r);
$cast(G_PTR, H2_PTR);
$display("Output from process_common with G input:");
G_PTR.g();
end
endmodule
多态-dynamic dispatch
function automatic H process_common(input H input_h);
H output_h;
input_h.f();
output_h = input_h;
return output_h;
endfunction
在上面的process_common调用中,在调用input_h.f()中,可以分几步:
step1: 判断f是否是虚函数,如果没有虚函数修饰,直接调用H.f(x);如果有虚函数修饰,则执行下一步。
step2:判断H的句柄指向哪个对象
step3:根据虚函数表,决定要调用基类的还是子类的具体函数。
其他问题
虚函数表是全局的(所有继承基类的Object共享),还是per-object的?