| |
在看OVM cookbook第二章,OOP,又要理解变态的继承、多态、虚函数等概念。
百度上搜索了好几个关于多态、重载、重写的概念和定义,但是目前我的理解并没有取得统一。只有下列结论:
根据程序运行时刻的对象来调用函数,这就是多态
SV里面多态是这样的规则:如果函数加了virtual关键字,那么就是根据当前指针指向哪个类的方法就调用哪个类的;如果没加,那么就根据该指针的类型来决定调用对应类的方法。下面的例子摘自本书第二章,figure->polygon->square,每个类中draw方法加virtual,而compute_area没加,主程序定义了三种类的指针f,p,s,并且f和p都指向s,那么最后执行的结果就是:
square::draw
polygon::compute_area
square::draw
figure::compute_area
square::draw
square::compute_area
compute_area方法没加virtural,是编译时决定
draw方法加了virtual,是运行时决定,都指向s,所以调用square的方法
class figure;
virtual function void draw();
$display("figure::draw");
endfunction
function void compute_area();
$display("figure::compute_area");
endfunction
endclass
class polygon extends figure;
virtual function void draw();
$display("polygon::draw");
endfunction
function void compute_area();
$display("polygon::compute_area");
endfunction
endclass
class square extends polygon;
virtual function void draw();
$display("square::draw");
endfunction
function void compute_area();
$display("square::compute_area");
endfunction
endclass
program top;
figure f;
polygon p;
square s;
initial begin
s = new();
f = s;
p = s;
p.draw();
p.compute_area();
f.draw();
f.compute_area();
s.draw();
s.compute_area();
end
endprogram