【发布时间】:2015-06-30 13:48:09
【问题描述】:
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
在一本教科书中,“编程语言的概念,第 10 章”,
有一部分是关于动态方法绑定的。
我认为 rect 指向的对象的类型无法静态解析,因为 rect 是多态引用类型。 rect 也可能在运行时引用 Sqaure 类型的对象。
代码上面最后一行不正确??
【问题讨论】:
-
我修好了,有错误
-
一个足够聪明的优化器可能能够证明
rect在这个例子中总是指向Rectangle的一个实例,并静态绑定到Rectangle::draw。无论哪种方式,可观察到的效果都是相同的,所以不清楚你为什么会关心。
标签: c++ dynamic-binding