1
2
|
typedef void (Base::*bfnPrint)();
bfnPrint func = ::Print;
|
就是说虽然函数指针func取值对象用的是父类.
但是如果Print函数是虚函数,
利用子类实例调用func函数的时候,实际上会调用到子类的Print函数.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
// virtual_functions.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
class Base
{
public:
virtual void Print();
};
void Base :: Print()
{
cout << "Print function for class Base\n";
}
class Derived : public Base
{
public:
virtual void Print();
};
void Derived :: Print()
{
cout << "Print function for class Derived\n";
}
int main()
{
Base bObject;
Derived dObject;
typedef void (Base::*bfnPrint)();
bfnPrint func = &Base::Print;
(&bObject->*func)();
(&dObject->*func)();
}
|
print out
1
2
|
Print function for class Base
Print function for class Derived
|