一个C++执行过程 关于虚拟函数
代码如下:

主函数中调用了a.fun1(&b);将对象b的地址传递给函数对象a的fun1函数,
然后开始执行函数a.fun1(animal *maybedog_maybehorse),此处fun1的形参是一个animal类型的指针。
用这个指针存储对象b的地址。
问题一:a.fun1函数内容是maybedog_maybehorse->born(); 是不是代用了对象b的born函数??????
问题二:类animal 和类horse中都有成员函数born,类horse公开继承了类animal。那么这两个born函数有什么关系吗。
问题三:两个类(animal和 horse)中的born 都是 虚函数。此处虚函数起到一个什么作用呢?
无知小白问了一个简答问题,还望各位大牛给点帮助。
谢谢
#include <iostream.h>
//using namespace std;
class animal
{
public:
animal();//声明一个构造函数
~animal();//声明一个析构函数
void fun1(animal *maybedog_maybehorse);//定义了一个函数 形参是一个 animal类型的指针
virtual void born();//定义了一个虚函数 born
};
//以下内容是 类class里面的成员函数的定义
void animal::fun1(animal *maybedog_maybehorse)
{
maybedog_maybehorse->born();
}
animal::animal(){cout<<"执行类animal的构造函数"<<endl;}//一个空的构造函数
animal::~animal(){cout<<"执行类animal的析构函数"<<endl;}//一个空的析构函数
void animal::born()
{
cout<<"animal"<<endl;
cout<<"执行类animal的born函数"<<endl;
}
//以上完成了类animal的全部定义。
//以下定义了一个类horse ,该类从类animal继承下来。
class horse:public animal
{
public:
horse();//声明构造函数
~horse();//声明析构函数
virtual void born();//声明一个虚函数 born
};
horse::horse(){cout<<"执行类horse的构造函数"<<endl;} //类horse的构造函数定义
horse::~horse(){cout<<"执行类horse的析构函数"<<endl;}//类horse的析构函数的定义
void horse::born()
{
cout<<"horse"<<endl;
cout<<"执行类horse的born函数"<<endl;
}
//以上完成了类horse的全部定义
//以下正式进入主函数 main
int main()
{
cout<<"进入main函数"<<endl;
animal a;//定义类animal的一个实例对象 a;
cout<<"完成a定义"<<endl;
horse b;//定义类horse的一个实例对象 b;
cout<<"完成b定义"<<endl;
a.fun1(&b);//将对象b的地址传递给函数对象a的fun1函数
cout<<"主函数完成调用对象a的是fun1函数"<<endl;
cout<<"******************"<<endl;
return 0;
}

主函数中调用了a.fun1(&b);将对象b的地址传递给函数对象a的fun1函数,
然后开始执行函数a.fun1(animal *maybedog_maybehorse),此处fun1的形参是一个animal类型的指针。
用这个指针存储对象b的地址。
问题一:a.fun1函数内容是maybedog_maybehorse->born(); 是不是代用了对象b的born函数??????
问题二:类animal 和类horse中都有成员函数born,类horse公开继承了类animal。那么这两个born函数有什么关系吗。
问题三:两个类(animal和 horse)中的born 都是 虚函数。此处虚函数起到一个什么作用呢?
无知小白问了一个简答问题,还望各位大牛给点帮助。
谢谢
...全文


