SystemVerilog this 关键字:引用当前对象
this 是 class 内指向当前对象的句柄。它最常用于解决参数名与成员名冲突,也可用于把当前对象作为参数传递。
1. 区分同名变量
1 | class packet; |
不加 this 时,addr = addr 只是参数自赋值,成员保持默认值。
2. 传递当前句柄
1 | class node; |
3. 链式调用
1 | function packet set_addr(bit [31:0] a); |
4. 常见误区
- 认为 this 会创建新对象:它只是引用。
- 在静态方法中写 this:非法。
- 用 this 比较对象内容:
this == other比较句柄,不是字段。
小结
this 解决“我在说谁”的问题。同名遮蔽、传递自身、链式返回是三个最实用的场景。
参考文献:ChipVerify SystemVerilog Tutorial — SystemVerilog ‘this’ keyword 章节(https://chipverify.com/systemverilog/systemverilog-this-keyword)。本文为原创中文讲解。