You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SystemVerilog构造器返回值链式调用报错问题咨询

SystemVerilog构造器无法直接链式调用的原因及解决方法

问题原因

SystemVerilog的语法规则对new()构造方法的调用有特殊限制:虽然new()确实会返回对象引用,但它不能直接作为成员方法调用的目标(即不能在new()后直接跟.调用方法)。语法解析器会将MyPacket::new().not_fun_ction()这种写法误判为非法语法,因为它无法识别new()的返回值是一个可直接调用方法的对象引用表达式——只有当这个返回值被赋值给变量,或者被括号明确包裹为一个完整表达式时,解析器才能正确处理。

解决方法

要实现单语句的链式调用,有两种可行方案:

方案1:用括号包裹构造器调用

把new()调用放在括号里,让解析器明确将其视为一个完整的对象引用表达式,之后即可链式调用成员方法:

class MyPacket;
  function MyPacket not_fun_ction();
    $display("not fun");
    return this;
  endfunction
endclass

module testbench;
  MyPacket temp;
  initial
  begin
    temp = (MyPacket::new()).not_fun_ction().not_fun_ction();
  end
endmodule

方案2:使用静态工厂方法

在类中定义一个静态工厂方法,内部调用new()并返回对象引用,通过工厂方法来实现链式调用:

class MyPacket;
  static function MyPacket create();
    create = new();
  endfunction

  function MyPacket not_fun_ction();
    $display("not fun");
    return this;
  endfunction
endclass

module testbench;
  MyPacket temp;
  initial
  begin
    temp = MyPacket::create().not_fun_ction().not_fun_ction();
  end
endmodule

内容的提问来源于stack exchange,提问作者G. B.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 00:50:01