class constrainend;
rand bit x;
rand bit [1:0] y;
constraint c_xy //对x,y定义约束{(x==0)-> y==0;
}
endclass
program test;
constrainend p;
initial begin
p=new();
p.c_xy.constraint_mode(0);// 将实例p中对x,y的约束关闭assert(p.randomize() with {x==0; y==0;});//随机化x,y,并添加一个新约束
$display("x = %d",p.x);//不会再被原类中的约束限制,而是被randomzie_with约束限制
$display("y = %d",p.y);
end
endprogram
子类extends父类,定义同名约束来覆盖父类约束
class constrainend;
rand bit x;
rand bit [1:0] y;
constraint c_xy
{(x==0)-> y==0;
}
endclass
class overwrite extends constrainend;//子类继承父类,会继承属性和方法,所以父类的约束也继承了
constraint c_xy //子类如果想定义一个新约束覆盖父类,则需要定义一个同名约束{
x==0;
y==0;
}
endclass
program test;
overwrite p;
initial begin
p=new();assert(p.randomize());//在子类约束的基础上随机化
$display("x = %d",p.x);
$display("y = %d",p.y);
end
endprogram