SV学习:从头开始了解数据类型 - 2. 自定义数据类型
最编程
2024-01-22 18:22:49
...
在SV使用typedef关键字进行用户自定义类型的扩展。定义新的数据类型可以提高代码的可读性,复杂的数据类型(结构体、联合体)和特定的数组可以通过使用一个简单易懂的名字(别名)被定义为一个新的数据类型,这个新的类型就可以定义对应的变量:
typedef int my_favorite_type;
my_favorite_type a, b;
这样的方法不是创建新的数据类型,只是在做文本替换;将一个特定的数组定义为新的数据类型:
parameter OPSIZE = 8;
typedef reg [OPSIZE-1: 0] opreg_t;
opreg_t op_a, op_b;
如果使用空的typedef事先对一个数据类型作出标识,那么它就可以在其定义之前使用:
typedef foo;
foo f = 1;
typedef int foo;
一个用户自定义类型需要在类型的内容被定义之前声明。这对于由enum、sturct、union、class派生出的用户自定义类型很有用处:
typedef enum type_declaration_identifier;
typedef struct type_declaration_identifier;
typedef union type_declaration_identifier;
typedef class type_declaration_identifier;
typedef type_declaration_identifier;
某些情况下,定义一个新的数据类型是必须的,因为在SV中要用过数据类型的标识符才可以做类型转换:
// typedef_example
module test_typedef ();
typedef enum {red, green, blue, yellow, white, black} colors;
colors my_colors;
initial begin
$display ("my_colors's defaut value is %s", my_colors);
my_colors = green;
// my_colors = 1; // err 需要做数据类型转换
my_colors = colors'(3); // 通过colors数据类型标识符做类型转换
$display ("my_colors is %s", my_colors.name);
end
endmodule