class Shape {
public:
virtual void draw() = 0;
. . .
};
class Circle : public Shape {
public:
void draw() { . . . }
. . .
};
class Rectangle : public Shape {
public:
void draw() { . . . }
. . .
};
class Square : public Rectangle {
public:
void draw() { . . . }
. . .
};
Rectangle* rect = new Rectangle;
rect->draw(); // Statically bound to the draw in the Rectangle class
In a text book , "concepts of programming language, 10th",
there's a part about dynamic method binding.
i think the type of the object pointed by rect can't be resolved statically because rect is polymorhpic reference type. rect might also reference Sqaure type object in run time.
the last line above the code is incorrect??
答案 0 :(得分:2)
Consider the following example
int main
{
Shape* cir = new Circle;
Shape* rec = new Rectangle;
Shape* sqr = new Square;
cir->draw(); // Circle::draw
rec->draw(); // Rectangle::draw
sqr->draw(); // Square::draw
}
All of these variables cir
, rec
, and sqr
are Shape*
, but they will invoke their respective draw
method due to polymorphism. This is even more clear when we re-use the same variable
int main
{
Shape* shape = new Circle;
shape->draw(); // Circle::draw
delete shape;
shape = new Rectangle;
shape->draw(); // Rectangle::draw
delete shape;
shape = new Square;
shape->draw(); // Square::draw
delete shape;
}
In this case, the draw
function must be resolved during runtime because the underlying type of shape
can be modified throughout the runtime.
答案 1 :(得分:0)
There's no problem with your code, for polymorphic classes virtual
function calls are resolved at runtime using the virtual function table, in fact, that is called dynamic binding in c++
.
答案 2 :(得分:0)
从概念上讲,因为draw()是一个虚方法,rect->draw()
将始终参考由vtable
指向的Rectangle
派生对象的rect
。
然而
如果编译器可以证明rect
实际上指的是Rectangle
的实例,而不是某个其他派生的类,它覆盖了draw()
方法,那么它允许(但不是必需)绕过多态查找,从而节省了几次内存提取。