64,643
社区成员
发帖
与我相关
我的任务
分享
#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;
}
void animal::fun1(animal *maybedog_maybehorse)
{
maybedog_maybehorse->born(); //这里的maybedog_maybehorse是基类animal的指针。但具体调用基类animal的born还是子类horse的born主要看maybedog_maybehorse是用什么构造的。本例中你实际传入的参数是horse的指针,所以它调用的就是horse的born。要出现以上特性,就必须在基类的同名函数上加上virtual关键字。子类的同名函数born其实加不加这个关键字都可以。
}
再举个具体的例子
struct Base
{
virtual void foo() const {};
}
struct Derive : Base
{
void foo() const {};
}
int main()
{
Base * B = new Base;
Base * D = new Derive;
B -> foo(); //这个调用的就是Base的foo
D -> foo(); //这个调用的就是Derive的foo,虽然它和B同样都是指向Base的指针。
return 0;
}
#include <iostream>
using namespace std;