http://baike.baidu.com/link?url=heYKUVZNDYa2dR2slQccCLhDvoQ47KQQkmibQpOUPaFlKnHTwO6NeWxBBd_H4EEP
目錄
1定義編輯
2作用編輯
3示例編輯
實例
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
|
#include<iostream> usingnamespacestd; classCshape { public : voidSetColor(intcolor){m_nColor=color;} virtualvoidDisplay( void ){cout<< "Cshape" <<endl;} private : intm_nColor; }; classCrectangle:publicCshape{ public : virtualvoidDisplay( void ) { cout<< "Crectangle" <<endl; } }; classCtriangle:publicCshape{ virtualvoidDisplay( void ) {cout<< "Ctriangle" <<endl;} }; classCellipse:publicCshape{ public : virtualvoidDisplay( void ) {cout<< "Cellipse" <<endl;} }; voidmain(){ CshapeobShape; CellipseobEllipse; CtriangleobTriangle; CrectangleobRectangle; Cshape*pShape[4]={&obShape,&obEllipse,&obTriangle,&obRectangle}; for (inti=0;i<4;i++) pShape[i]->Display(); } |
條件
4c++的編輯
一,定義
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
|
classA { public : voidprint(){cout<< "ThisisA" <<endl;} }; classB:publicA { public : voidprint(){cout<< "ThisisB" <<endl;} }; intmain() { //爲了在以後便於區分,我這段main()代碼叫做main1 Aa; Bb; a.print(); b.print(); } |
1
2
3
4
5
6
7
8
|
intmain(){ //main2 Aa; Bb; A*p1=&a; A*p2=&b; p1->print(); p2->print(); } |
1
2
3
4
5
6
7
8
|
classA{ public : virtualvoidprint(){cout<< "ThisisA" <<endl;} //現在成了虛函數了 }; classB:publicA{ public : voidprint(){cout<< "ThisisB" <<endl;} //這裏需要在前面加上關鍵字virtual嗎? }; |
二, 實現
1
2
3
4
5
6
7
8
9
10
|
classA{ //虛函數示例代碼 public : virtualvoidfun(){cout<<1<<endl;} virtualvoidfun2(){cout<<2<<endl;} }; classB:publicA{ public : voidfun(){cout<<3<<endl;} voidfun2(){cout<<4<<endl;} }; |
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#include<iostream> usingnamespacestd; //將上面“虛函數示例代碼”添加在這裏 intmain(){ void (*fun)(A*); A*p=newB; longlVptrAddr; memcpy (&lVptrAddr,p,4); memcpy (&fun, reinterpret_cast < long *>(lVptrAddr),4); fun(p); deletep; system ( "pause" ); } |
三, 代碼示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#include<iostream> usingnamespacestd; classA{ //虛函數示例代碼2 public : virtualvoidfun(){cout<< "A::fun" <<endl;} virtualvoidfun2(){cout<< "A::fun2" <<endl;} }; classB:publicA{ public : voidfun(){cout<< "B::fun" <<endl;} voidfun2(){cout<< "B::fun2" <<endl;} }; //end//虛函數示例代碼2 intmain(){ void (A::*fun)(); //定義一個函數指針 A*p=newB; fun=&A::fun; (p->*fun)(); fun=&A::fun2; (p->*fun)(); deletep; system ( "pause" ); } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#include<iostream> usingnamespacestd; //將上面“虛函數示例代碼2”添加在這裏 voidCallVirtualFun( void *pThis,intindex=0){ void (*funptr)( void *); longlVptrAddr; memcpy (&lVptrAddr,pThis,4); memcpy (&funptr, reinterpret_cast < long *>(lVptrAddr)+index,4); funptr(pThis); //調用 } intmain(){ A*p=newB; CallVirtualFun(p); //調用虛函數p->fun() CallVirtualFun(p,1); //調用虛函數p->fun2() system ( "pause" ); } |