9. Member Function's Inherit (1)
struct A { void A_real_method_a( void* p) {
int a; struct A* this = p;
FP method_a; printf("this is method_a %dn",this>a);
}; }
struct B { void B_real_method_b( void* p) {
struct A parent; struct B* this = p;
int b; printf("this is method_b %dn",this>b);
FP method_b; }
};
int main() { void a_init( struct A* a) {
struct B b; a > a = 1;
a_init( &b ); a > method_a = A_real_method_a;
b_init( &b ); }
void b_init( struct B* b) {
struct A* ap = &b; b > b = 2;
b > method_b = B_real_method_b;
ap > method_a( ap ); }
b . method_b( &b );
};
elpam.tw@gmail.com
10. Member Function's Inherit (2)
/* 24.c */
int main()
●
Child 如果希望執行 ( 存取 ) {
struct B b;
Parent 的函式 ( 變數 ) ,需要 a_init( &b );
先 Cast 成 Parent 再執行 ( 存 b_init( &b );
取) struct A* ap = &b;
ap > method_a( ap );
b . method_b( &b );
};
#> ./24
this is method_a 1
this is method_b 2
#>
elpam.tw@gmail.com
11. 結論
●
我們可以實作 class_init() 時將 class 內的
member value and member function 都設定好
– 也就是 ''Constructor''
● 自已實作 C 不提供的 Member Function!!
elpam.tw@gmail.com
12. Implement Virtual Function
25.c
● Child 的 init 可以將 Parent 的 Member Function
做改寫的動作,以達到 Virtual Function 的效果
– 下一頁粉紅色的那一行
elpam.tw@gmail.com
13. Virtual Function (1)
void A_real_method_a( void* p)
{
struct A* this = p;
printf("this is %s %dn"
,__FUNCTION__,this>a); void A_init( struct A* a)
} {
void B_real_method_a( void* p) a > a = 1;
{ a > method_a = A_real_method_a;
struct B* this = p; }
printf("this is %s %dn"
,__FUNCTION__,this>b);
} void B_init( struct B* b)
void B_real_method_b( void* p) {
{ struct A* a = b;
struct B* this = p; b > b = 2;
printf("this is %s %dn" a > method_a = B_real_method_a;
,__FUNCTION__,this>b); b > method_b = B_real_method_b;
} }
elpam.tw@gmail.com
14. Virtual Function (2)
●
A_init 一定要比 B_init 先執行
– Parent 的 Constructor 需要先執
行 /* 25.c */
int main()
{
struct B b;
#> ./25 A_init( &b );
this is A_real_method_a 1
this is B_real_method_a 2 struct A* ap = &b;
this is B_real_method_b 2 ap > method_a( ap );
#>
B_init( &b );
ap > method_a( ap );
b . method_b( &b );
};
elpam.tw@gmail.com
16. Constructor in C (1)
● we use PREFIX_new to replace malloc
– 所有的物件都以 PREFIX_NEW 產生,以確保
Constructor 被正確的執行
struct A{ struct A* A_new()
int a; {
int b; struct A* ret = malloc( sizeof(A) );
}; ret > a = 0;
ret > b = 1;
return ret;
}
elpam.tw@gmail.com