#include <iostream.h>
// `(*∩_∩*)
C++类指针指向子类还是基类的判断方法#include <iostream.h> class animal { public: animal() { cout<<"hello kitty"<<endl; } virtual void eat() { cout<<"eat bianbian"<<endl; } }; class plant:public animal { public: plant() { } void eat() { cout<<"haha"<<endl; } }; void fn(animal *pan) { pan->eat (); } void main() { plant st; animal*pan; //一个指向animal的指针 pan=&st; //把这个指针换成plant的类空间 fn(pan);//把这个被替换的指针赋给fn(),它貌似指向了,然后通过这个函式指向eat() } //函数中有两个类,而且都有eat()函数最后到底指向哪个eat()呢! //答:指向基类。如果想指向子类,办法是有的!就是把基类的eat()函数虚化。加virtual前缀即可! // `(*∩_∩*) |
|