|
|
刚写了下看看。
class B和C都继承A。现在实例化C,然后用一个A成员函数指针指向B的成员函数(类型转换),然后用C的实例调用,于是相当于C的实例调用了B的成员函数。
弹出的对话框标题为"this is B::bfunc",内容却是C的private成员"ccc"。
- #include <windows.h>
- class A
- {
- private:
- LPSTR s;
- public:
- A(){s="aaa";}
- void afunc()
- {
- MessageBox(NULL,s,"this is A::afunc",MB_OK);
- }
- };
- [color=#339900]/*B继承A*/[/color]
- class B:public A
- {
- private:
- LPSTR s;
- public:
- B():A(){s="bbb";}
- void bfunc()
- {
- MessageBox(NULL,s,"this is B::bfunc",MB_OK);
- }
- };
- [color=#339900]/*C继承A*/[/color]
- class C:public A
- {
- private:
- LPSTR s;
- public:
- C():A(){s="ccc";}
- void cfunc()
- {
- MessageBox(NULL,s,"this is C::cfunc",MB_OK);
- }
- };
- typedef void (A::*LPDELEGATEAFUNC)(void);
- [color=#339900]/*WinMain*/[/color]
- int WINAPI WinMain(HINSTANCE hInst,HINSTANCE,LPSTR CmdLine,int CmdShow)
- {
- [color=#339900]/*实例化C*/[/color]
- C* c=new C();
- [color=#339900]/*A成员函数指针指向B的成员函数*/[/color]
- LPDELEGATEAFUNC pf=(LPDELEGATEAFUNC)B::bfunc;
- [color=#339900]/*用C的实例调用该函数*/[/color]
- (c->*pf)();
- }[color=#339900]/*WinMain*/[/color]
复制代码 |
|