#include<iostream>
using namespace std;
class Base
{
private:
int _base ;
public:
Base()
:_base (0)
{}
virtual void show()
{
cout << "Base::show()" << endl ;
}
//....
};
class D :public Base
{
public:
D()
:_d (1)
{}
void show()
{
cout << "D::show()" << endl ;
}
private:
int _d ;
};
void Print (Base *pb)
{
pb-> show();
}
int main ()
{
Base b;
D d;
Print(& b);
Print(& d);
getchar();
return 0;
}
#include<iostream>
using namespace std;
typedef void (*PTR)();
class Base
{
private:
int _base ;
public:
Base()
:_base (0)
{}
virtual void show()
{
cout << "Base::show()" << endl ;
}
//...
};
class Base2
{
private:
int _base2 ;
public:
Base2()
:_base2 (2)
{}
virtual void show()
{
cout << "Base2::show()" << endl ;
}
virtual void fun2()
{
cout << "Base2::fun2()" << endl ;
}
//...
};
class D :public Base,public Base2
{
public:
D()
:_d (1)
{}
void show()
{
cout << "D::show()" << endl ;
}
void fun2()
{
cout << "D::fun2()" << endl ;
}
virtual void fun3()
{
cout << "D::fun3()" << endl ;
}
virtual void fun4()
{
cout << "D::fun4()" << endl ;
}
private:
int _d ;
};
void PrintVT (int p )
//实参是每个类存储虚函数指针的地址,解引用之后代表该类的虚函数指针
{
PTR ptr = NULL;
//现在让pi能访问类的虚函数指针
int *pi = (int *)p;
int i = 0;
while (pi [i ])
{
ptr = (PTR)pi[i];
ptr();
i++;
}
}
int main ()
{
//Base b;
//Base2 b2;
D d;
//PrintVT(*(int *)&b);
//cout << "--------------------" << endl;
//PrintVT(*(int *)&b2);
//cout << "--------------------" << endl;
PrintVT(*( int *)&d );
cout << "--------------------" << endl ;
getchar();
return 0;
}
*我们发现在派生类中有两个虚函数表,并且派生类自己的虚函数被存入了第一个虚函数表