<pre name="code" class="cpp">/*不使用virtual关键字 ,模拟虚函数来表现出多态性:
写一基类Person 有sayHello,sayGoodbye函数
有一子类student 它也有自己的sayHello, sayGoodbye函数
请在这两个类里加入函数 vsayHello, vsayGoodbye函数
来表现出对象的多态性(分别调用自己的对应的sayHello和sayGoodbye)
分别使用静态成员函数指针,和成员函数指针完成
*/
#include "stdafx.h"
#include <IOSTREAM>
using namespace std;
class Person;
class student;
typedef void (Person::*FUNTYPE)();
typedef void (student::*FUNTYPE2)();
//VC编译器的实现:如果类中有虚函数,在实例化对象时,对象的首地址处存放虚表地址
//而且地址指向的是全局数据区,那么我们在模拟的时候可以用全局指针,或者静态成员指针
class Person
{
public:
Person()
{
m_lpVtable = m_lpPersonTable;
}
~Person()
{
m_lpVtable = m_lpPersonTable;
}
void sayHello()
{
cout << "Person::sayHello()" << endl;
}
void sayGoodbye()
{
cout << "Person::sayGoodbye()" << endl;
}
void vsayHello()
{
(this->*m_lpVtable[0])();
}
void vsayGoodbye()
{
(this->*m_lpVtable[1])();
}
protected:
FUNTYPE *m_lpVtable;
static FUNTYPE m_lpPersonTable[];
};
//静态数据成员赋值
FUNTYPE Person::m_lpPersonTable[] = {Person::sayHello, Person::sayGoodbye};
class student :public Person
{
public:
student()
{
m_lpVtable = (FUNTYPE*)m_lpStudentTable;
}
~student()
{
m_lpVtable = (FUNTYPE*)m_lpStudentTable;
}
void sayHello()
{
cout << "student::sayHello()" << endl;
}
void sayGoodbye()
{
cout << "student::sayGoodbye()" << endl;
}
void vsayHello()
{
}
void vsayGoodbye()
{
}
public:
static FUNTYPE2 m_lpStudentTable[];
};
FUNTYPE2 student::m_lpStudentTable[] = {student::sayHello, student::sayGoodbye};
int main(int argc, char* argv[])
{
Person per;
student stu;
Person *lpPerson = NULL;
lpPerson = &per;
lpPerson->vsayHello();
lpPerson->vsayGoodbye();
lpPerson = &stu;
lpPerson->vsayHello();
lpPerson->vsayGoodbye();
return 0;
}
//上面的vsayHello,和vsayGoodbye是为了实现更简单!我们访问虚表的函数,可以直接用下面的方法!
(lpPerson->*lpPerson->m_lpVtable[0])();
(lpPerson->*lpPerson->m_lpVtable[1])();
访问类的成员函数指针!(当然也包含数组的下标寻址方式)