casting - SystemVerilog 支持向下转型吗?

标签 casting system-verilog

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/

相关文章:

python - Mysql 在一个查询中进行转换和比较?

c++ - 将指向成员函数的指针转换为普通指针

oop - 类的对象在其类结束类定义中的含义是什么?

verilog - systemverilog 中的重复运算符

system-verilog - 仅为 uvm 中的少数/序列/对象/接口(interface)设置详细程度?

java - 转换为父类(super class)后从子类获取数据

java - 如何在java中将数据集复制或转换为Arraylist?

system-verilog - 何时评估断言 "disable iff"值?

system-verilog - 生成封面所需时间的重要性

Java 转换对象