C++类的继承的一个问题
如下C++代码:
#include <iostream.h> class animal { public: animal(); ~animal(); void fun1(animal *maybedog_maybehorse); void born(); }; void animal::fun1(animal *maybedog_maybehorse) { maybedog_maybehorse->born(); } animal::animal() { }animal::~animal() { } void animal::born() { cout<< "animal"; } ////////////////////////horseclass horse:public animal { public: horse(); ~horse(); void born(); }; horse::horse() { } horse::~horse() { } void horse::born(){ cout<<"horse"; } ////////////////////mainvoid main() { animal a; horse b; a.fun1(&b); } horse b; animal *maybedog_maybehorse=&b 执行的必然是父类的方法修改如下class animal { public: animal(); ~animal(); void fun1(animal *maybedog_maybehorse); virtual void born(); }; 输出 horse
[解决办法]
上面几位说的都对,虚函数的问题。如果是你的程序的话,是输出animal的。。。