gpt4 book ai didi

casting - SystemVerilog 支持向下转型吗?

转载 作者:行者123 更新时间:2023-12-02 15:27:13 25 4
gpt4 key购买 nike

SystemVerilog 是否支持向下转型(将基础对象转型为派生对象)?如果是这样,怎么办?

下面的沮丧示例不起作用:

class base;
int a = 5;
endclass

class extend extends base;
int b = 1;
endclass

module test;

initial begin
base m_base;
extend m_extend;

m_base = new();
m_extend = new();
$cast(m_extend, m_base);
$display(m_extend.a);
end
endmodule

修改并重新运行 EDA Playground 上的示例:http://www.edaplayground.com/s/4/581

最佳答案

是的,你可以沮丧。您的示例是正确的语法,并且它实际上可以编译。但是,由于转换失败,您会收到运行时错误。

您示例中的强制转换失败,因为只有当基础对象的句柄实际引用派生类型的对象时,您才能成功向下强制转换。您可以将 $cast 作为函数调用,它将返回一个 bool 值,指示转换是否成功。

这是一个例子:

class animal;
function void eat();
endfunction
endclass

class dog extends animal;
function void bark();
$display("woof");
endfunction
endclass

class cat extends animal;
function void meow();
$display("meow");
endfunction
endclass

module test;

initial begin
dog a_dog = new();
cat a_cat = new();

animal animals[$];
animals.push_back(a_dog);
animals.push_back(a_cat);

foreach (animals[i]) begin
dog another_dog;
animals[i].eat();
if ($cast(another_dog, animals[i])) begin
$display("Found a dog!");
another_dog.bark();
end
end

end
endmodule

输出:

# Found a dog!
# woof

参见http://www.edaplayground.com/s/474/586

关于casting - SystemVerilog 支持向下转型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20548473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com