Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

C++ªº±j¨îÂ૬¨ì©³°µ¤F¨Ç¤°»ò

0 views
Skip to first unread message

新年新希望

unread,
Feb 22, 2003, 1:24:08 PM2/22/03
to
其實有個重點大家是不是有注意到
即使new一個base class 然後轉型成sub class
call sub class is still working...
it is beacause there are nothing with the "object".
Compilier uses name mangling tech to change the member function
to global and unique C function with this pointer( non static has only ).

Of course, u could try to new a A.. and downcast it to B then access b
variable. However, it might be crash by accessing undefinitive mem space.

《 在 WESLE...@snow.ice.ntnu.edu.tw (遊戲般的小步舞曲) 的大作中提到: 》
: ==> 在 hacpe...@bbs.kimo.com.tw (到什麼時候ㄋ??) 的文章中提到:
: : C++的強制轉型到底做了些什麼
: : #include<stdio.h>
: : class A
: : {
: : public:
: : int a ;
: : void fun1(){printf("A::fun1()\n");}
: : };
: : class B : public A
: : {
: : public:
: : int b ;
: : void fun2(){printf("B::fun2()\n");}
: : };
: : main()
: : {
: : A* ptr = new A ;
: : (*ptr).fun1();
: : (*(B*)ptr).fun2();
: : return 0 ;
: : }
: : ptr本來是一個指向A的pointer
: : 但是
: : 經過強制轉型後
: : 他竟然
: : 神奇的可以找到fun2()的位址
: : 這在C根本是不可能會發生的
: : 在C
: : 這種指向比原本預設更大的區塊
: : 只會讓指標指向一塊未知的區域
: : 但是
: : 在C++ .....
: : 這其中到底ㄉ發生了什麼事呢??
: 這件事其實也沒那麼神奇啦...
: 在這個例子裡它轉型時做的事是和C是一樣的囉...
: 你已經在程式裡明白告訴compiler你要這樣轉..
: compiler是不會拂逆你的意思的..
: 不過降子用會不會有問題..是你(programmer)應該承擔的..:)
: 所以compiler不會給你什麼warning囉
: 至於能用到B::fun2()也沒那麼神奇啦
: 因為compiler做出來的...概念上是把它當成一個類似以下的function
: void B_fun2(B* this) { printf("B::fun2()\n") ; }
: 在呼叫時是會把ptr當成那個this傳入..
: 既然你fun2裡面沒有用到B的member
: 也就不會發生什麼錯誤啦..
: 最後的重點是...別寫出降子的程式...:)


--
[m [1;31m※ 來源:‧蛋捲廣場 bbs.tku.edu.tw‧[FROM: 61.64.100.93] [m

0 new messages