在C++中,对象分为静态类型(static type)和动态类型(dynamic type)。静态类型就是在程序中被声明时所采用的类型;而动态类型则是指“目前所指对象的类型”,它可以表现出一个对象将会有什么行为。
class Shape {
public:
virtual display(int i = 4) {
std::cout << "in Shape i is " << i << std::endl;
}
...
};
class Circle : public Shape {
public:
virtual display(int i = 6) {
std::cout << "in Circle i is " << i << std::endl;
}
...
};
class Rectangle : public Shape {
public:
virtual display(int i = 8) {
std::cout << "in Rectangle i is " << i << std::endl;
}
...
};
Shape* ps;
Shape* pt = new Rectangle;
Shape* pc = new Circle;
上面的代码中,ps、pt、pc的静态类型都是Shape,而pt、pc的动态类型则分别时Rectangle和Circle,ps没有动态类型,因为它尚未指向任何对象。
对于类中的virtual函数,是动态绑定(dynamically bound)