参考绿皮书8.3;参考博文 基类句柄可以指向扩展类对象(向下类型转换),但扩展类句柄不能指向基类对象(向上类型转换),除非基类句柄之前指向了一个扩展类或者扩展类的扩展类对象。
class bird;
virtual function void hungry();
$display("i am a bird, i am hungry");
endfunction
function void hungry2();
$display("i am a bird, i am hungry2");
endfunction
endclass
class parrot extends bird;
virtual function void hungry();
$display("i am a parrot, i am hungry");
endfunction
function void hungry2();
$display("i am a parrot, i am hungry2");
endfunction
endclass
class dog extends parrot;
virtual function void hungry();
$display("i am a dog, i am hungry");
endfunction
function void hungry2();
$display("i am a dog, i am hungry2");
endfunction
endclass
program ex;
bird A;
parrot B;
dog C;
initial begin
A = new();
B = new();
A.hungry();
A.hungry2();
B.hungry();
B.hungry2();
$display();
end
initial begin
A = new();
B = new();
A = B;
A.hungry();
A.hungry2();
B.hungry();
B.hungry2();
$display();
end
initial begin
A = new();
B = new();
if(!$cast(B, A))
$display("B = A, failed");
A.hungry();
A.hungry2();
B.hungry();
B.hungry2();
$display();
end
initial begin
A = new();
B = new();
A = B;
$cast(B, A);
A.hungry();
A.hungry2();
B.hungry();
B.hungry2();
$display();
end
initial begin
A = new();
B = new();
C = new();
A = C;
$cast(B, A);
A.hungry();
A.hungry2();
B.hungry();
B.hungry2();
$display();
end
endprogram
- $cast可以作为函数或者任务,根据上下文,函数有返回值,转换成功返回1否则为0;
- 虚函数的方法取决于句柄指向的对象类型,非虚函数方法取决于句柄类型;
- $cast可以转换的前提是源端指向的对象是目的端或目的端的扩展类
|