实践是最好的学习方式
例子:
#include <iostream>
using namespace std;
class Shape {
public :
Shape() {};
~Shape() {};
virtual void draw() {
cout<<"Shape draw..."<<endl;
};
};
class Rect : public Shape {
public :
Rect() {};
~Rect() {};
virtual void draw() {
cout<<"Rect draw..."<<endl;
};
virtual void size() {
cout<<"Rect size..."<<endl;
};
};
int main(int argc, char **argv)
{
Shape* shp = new Shape();
Rect rect;
*shp = rect; // 对象切割
shp->draw(); // 对应Shape draw函数
shp = ▭ // 多态
shp->draw(); // 对应Rect draw函数
return 0;
}
我的理解,不知道正确与否?
所谓对象切割:c++为Shape Rect分别为他们的对象分配的空间,Shape的对象在内存中的尺寸小于Rect,即当*shp = rect执行的时候,函数virtual void size() {......}是没有拷贝的,所以就形成了“切割”,而shp = &rect只是指向rect的地址,所以就形成了多态。