82 lines
1.0 KiB
C++
82 lines
1.0 KiB
C++
|
|
#include <stdio.h>
|
|
|
|
class A
|
|
{
|
|
public:
|
|
typedef void (A::*virt_method_ptr)();
|
|
|
|
virt_method_ptr m_pMethod;
|
|
|
|
public:
|
|
A()
|
|
{
|
|
m_pMethod = &A::func1;
|
|
}
|
|
|
|
void call_method_through_ptr()
|
|
{
|
|
(this->*m_pMethod)();
|
|
}
|
|
|
|
virtual void func1()
|
|
{
|
|
puts( "called A::func1()" );
|
|
}
|
|
|
|
virtual void func2()
|
|
{
|
|
puts( "called A::func2()" );
|
|
}
|
|
|
|
virtual void func3()
|
|
{
|
|
puts( "called A::func3()" );
|
|
}
|
|
};
|
|
|
|
class B : public A
|
|
{
|
|
public:
|
|
int nTestPrintMe;
|
|
|
|
public:
|
|
B( int n )
|
|
{
|
|
m_pMethod = reinterpret_cast<virt_method_ptr>(&B::func4);
|
|
nTestPrintMe = n;
|
|
}
|
|
|
|
virtual void func3()
|
|
{
|
|
puts( "called B::func3()" );
|
|
}
|
|
|
|
virtual void func4()
|
|
{
|
|
printf( "called B::func4( %d ) \n", nTestPrintMe );
|
|
}
|
|
};
|
|
|
|
int main ()
|
|
{
|
|
A *o = new B( 10 );
|
|
|
|
o->call_method_through_ptr();
|
|
|
|
o->m_pMethod = &A::func1;
|
|
o->call_method_through_ptr();
|
|
|
|
o->m_pMethod = &A::func2;
|
|
o->call_method_through_ptr();
|
|
|
|
o->m_pMethod = &A::func3;
|
|
o->call_method_through_ptr();
|
|
|
|
o->m_pMethod = reinterpret_cast<A::virt_method_ptr>(&B::func4);
|
|
o->call_method_through_ptr();
|
|
|
|
return 0;
|
|
}
|
|
|