Re: [問題] 關於Class指標的觀念

看板C_and_CPP (C/C++)作者 (「雄辯是銀,沉默是金」)時間11年前 (2013/08/30 11:54), 編輯推噓0(005)
留言5則, 2人參與, 最新討論串11/19 (看更多)
vc 版本, 運氣很好, 沒花太久時間。 vc 我不熟, 有什麼問題還請版友們提出。 env: vc2010 winxp 32bit #include <iostream> #include <cstdio> using namespace std; struct A { virtual void func() { printf("i: %d\n", i_); } void inc() { ++i_; } A() { i_=10; } private: int i_; }; int main() { void (A::*p)() = &A::func; //cout << "sizeof: " << sizeof(p) << endl; //cout << "sizeof: " << sizeof(A) << endl; //printf("addr: %p\n", p); //cout << "p:" << p << endl; //unsigned int addr = pp; //printf("addr: %p\n", pp); A a; (a.*p)(); unsigned int vptr_addr = *(unsigned int *)&a; cout << "vptr_addr:" << hex << vptr_addr << endl; unsigned int func_addr = *(unsigned int *)vptr_addr; cout << "func_addr:" << hex << func_addr << endl; a.inc(); __asm { lea ecx, a } #if 1 (*(void(*)())(func_addr) )(); A aa; __asm { lea ecx, aa } (*(void(*)())(func_addr) )(); __asm { lea ecx, a } (*(void(*)())(func_addr) )(); __asm { lea ecx, aa } (*(void(*)())(func_addr) )(); #endif return 0; } C:\&gt;cl□ c.cpp Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.30319.01 for 80x86 Copyright (C) Microsoft Corporation.□ All rights reserved. c.cpp C:\Program Files\Microsoft Visual Studio 10.0\VC\INCLUDE\xlocale(323) : warning C4530: 已使用 C++ 例外處理常式,但沒有啟用回溯語意 (Unwind Semantics)。請指定 /E Hsc Microsoft (R) Incremental Linker Version 10.00.30319.01 Copyright (C) Microsoft Corporation.□ All rights reserved. /out:c.exe c.obj C:\&gt;c i: 10 vptr_addr:41a1bc func_addr:4011a0 i: 11 i: 10 i: 11 i: 10 順便測試了 arm/g++ arm version by c++ c.arm: ELF 32-bit LSB executable, ARM, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.26, not stripped root@/home$ ./c.arm i: 10 vptr_addr:8cc8 func_addr:8b74 i: 11 i: 10 i: 11 i: 10 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.125.239.46 ※ 編輯: descent 來自: 59.125.239.46 (08/30 11:58)

08/31 21:36, , 1F
這個敘述 :
08/31 21:36, 1F

08/31 21:49, , 2F
(*(void(*)())(func_addr))();
08/31 21:49, 2F

08/31 21:50, , 3F
我用 Visual C++ 2008 可以正常執行.
08/31 21:50, 3F

09/05 11:26, , 4F
雖然無法理解 G 大對 "正常執行" 的定義.
09/05 11:26, 4F

09/05 11:26, , 5F
不過 d 大如果把printf("i: %d\n", i_); 改成 cout 會?
09/05 11:26, 5F
文章代碼(AID): #1I81Twa1 (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1I81Twa1 (C_and_CPP)