[問題] 請問一個com程式問題

看板C_and_CPP (C/C++)作者時間15年前 (2010/10/29 12:11), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/1
最近看Inside COM這本書,看了好幾章才突然想到一個應該是前面 章節就該想到的問題,為什麼元件的QueryInterface明明是回傳界 面的指標,又不是指向元件了,為何呼叫函式時會知道要呼叫的是 元件版本的呢? 程式碼如下: ................................................................................. // // IUnknown.cpp // To compile use: cl IUnknown.cpp UUID.lib // #include "stdafx.h" #include <iostream> #include <objbase.h> using std::cout; using std::endl; void trace(const char* msg) { cout << msg << endl ;} //Interfaces interface IX : IUnknown { virtual void __stdcall Fx() = 0 ; } ; // Forward references for GUIDs extern const IID IID_IX ; // // Component // class CA : public IX { //IUnknown implementation virtual HRESULT __stdcall QueryInterface(const IID& iid, void** ppv) ; virtual ULONG __stdcall AddRef() { return 0 ;} virtual ULONG __stdcall Release() { return 0 ;} // Interface IX implementation virtual void __stdcall Fx() { cout << "Fx" << endl ;} } ; HRESULT __stdcall CA::QueryInterface(const IID& iid, void** ppv) { if (iid == IID_IUnknown) { trace("QueryInterface: Return pointer to IUnknown.") ; *ppv = static_cast<IX*>(this) ; } else if (iid == IID_IX) { trace("QueryInterface: Return pointer to IX.") ; *ppv = static_cast<IX*>(this) ; } else { trace("QueryInterface: Interface not supported.") ; *ppv = NULL ; return E_NOINTERFACE ; } static_cast<IUnknown*>(*ppv)->AddRef() ; // See Chapter 4. return S_OK ; } // // Creation function // IUnknown* CreateInstance() { IUnknown* pI = static_cast<IX*>(new CA) ; pI->AddRef() ; return pI ; } // // IIDs // // {32bb8320-b41b-11cf-a6bb-0080c7b2d682} static const IID IID_IX = {0x32bb8320, 0xb41b, 0x11cf, {0xa6, 0xbb, 0x0, 0x80, 0xc7, 0xb2, 0xd6, 0x82}} ; // // Client // int main() { HRESULT hr ; trace("Client: Get an IUnknown pointer.") ; IUnknown* pIUnknown = CreateInstance() ; trace("Client: Get interface IX.") ; IX* pIX = NULL ; hr = pIUnknown->QueryInterface(IID_IX, (void**)&pIX) ; if (SUCCEEDED(hr)) { trace("Client: Succeeded getting IX.") ; pIX->Fx() ; // Use interface IX. } // Delete the component. delete pIUnknown ; system("PAUSE"); return 0 ; } ................................................................................. 在main裡的pIX->Fx(),為什麼會知道要呼叫的是CA覆寫的版本?明明QueryInterface 後,pIX拿到的是CA已經static cast後的IX物件,但是這又很奇怪了,介面是abstract class, 怎能生成物件? 先感謝肯回應的版友,最近看書發現超多問題,雖然都不影響主體,但真的非常多看不懂的地方... p.s. 我懂polymorphism,也知道vtbl,vptr,但現在父類別型態的指標應該並沒有指向子類 別的物件阿(?) -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 123.50.53.228 ※ 編輯: selection 來自: 123.50.53.228 (10/29 12:21) ※ 編輯: selection 來自: 123.50.53.228 (10/29 12:21)
文章代碼(AID): #1CoabWUe (C_and_CPP)
文章代碼(AID): #1CoabWUe (C_and_CPP)