首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++类的继承的一个有关问题

2012-04-15 
C++类的继承的一个问题如下C++代码:C/C++ code#include iostream.h class animal { public:animal()~an

C++类的继承的一个问题
如下C++代码:

C/C++ code
#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); } 


为什么输出是animal?

有木有哪位大侠能够给我详细解释一下呢,感激不尽~~~

[解决办法]
看看虚函数那章吧
[解决办法]
显然你没有使用虚函数,也就是没有采用动态绑定咯,所以你用什么指针类型调用就是什么咯。你fun1的参数是animal *类型,显然你要调用animal的born函数了。
[解决办法]
C/C++ code
horse b; animal *maybedog_maybehorse=&b 执行的必然是父类的方法修改如下class animal { public:      animal();      ~animal();      void fun1(animal *maybedog_maybehorse);      virtual void born(); }; 输出 horse
[解决办法]
上面几位说的都对,虚函数的问题。如果是你的程序的话,是输出animal的。。。

热点排行