MFC文檔視圖(四):類之間的調用

來源:互聯網
上載者:User
文章目錄
  • CWinApp中顯式調用其他類
  • CFrameWnd調用其他類
  • CView調用其它類
  • CDocument調用其它類
  • CWinApp中隱式調用CDocument

我們前面有講到4個關鍵的類CWinApp,CFrameWnd,CView,CDocument是互相關聯,那自然會涉及到互相調用.這裡為了方便還繼承用這個類名字來說明(實際上應該是用繼承自它們的子類的)

下面有2個全域函數可以得到CWinApp與CFrameWnd.全域函數嘛就是隨便哪裡都能調用的了.

1.CWinApp* pApp = AfxGetApp();

2.CMainFrame* pMain=(CMainFrame*) AfxGetMainWnd();

//你也可以先得到CWinApp然後間接得到CMainFrame* pMain=(CMainFrame*)pApp->m_pMainWnd;

 

 

CWinApp中顯式調用其他類

1.CWinApp調用CDocument

方法1:

CWinApp中有一個CSingleDocTemplate的指標,而CSingleDocTemplate中又有指向CDocument的指標.於是乎通過指標一路找下去自然就找著了.

POSITION pos = m_pDocTemplate->GetFirstDocPosition();

CDocument *pDoc = m_pDocTemplate->GetNextDoc(pos);

//其中m_pDocTemplate就是CSingleDocTemplate的指標.這裡的POSITION有點類似STL中的iterator(迭代器).

方法2:

CFrameWnd* pMain=(CFrameWnd*)CWinThread::m_pMainWnd;

CDocument* pDoc = (CDocument*)pMain->CFrameWnd::GetActiveDocument(); //通過CFrame間接調用

2.CWinApp調用CView

CFrameWnd* pMain=(CFrameWnd*)CWinThread::m_pMainWnd;

CView* pView = (CView*)pMain->CFrameWnd::GetActiveView(); //通過CFrame間接調用

 

CFrameWnd調用其他類

CView* pView = (CView*)CFrameWnd::GetActiveView();

CDocument* pDoc = (CDocument*)CFrameWnd::GetActiveDocument();

 

CView調用其它類

CMyDocument* pDoc = (CMyDocument*)GetDocument();

 

CDocument調用其它類

POSITION pos=CDocument::GetFirstViewPosition();  //一個文檔類可以對應多個CView,但一個CView只對對應一個文檔類
while(pos != NULL) {
CView *pView=CDocument::GetNextView(pos);

}

 

CWinApp中隱式調用CDocument

以命令訊息的路由例.本來正常的路由順序是CView --> CDocument -->CFrameWnd --> CWinApp.

仍為菜單File-->Open發出的訊息為例.假如你讓類CWinApp來處理這相訊息,那麼前面3個類就不能處理它了.那假如你只想CWinApp處理一部分.另一部分要其他類處理該咋整呢.

先在CMyWinApp中定義宏

ON_COMMAND(ID_FILE_OPEN, OnFileOpen)

void CMyWinApp:OnFileOpen(){

//做一些部分處理

CString szPath = _T("D:\\Test.txt");

CWinApp::OpenDocumentFile(szPath); //調用父類方法

}

假如類CMyDocument中有重寫父類的虛函數BOOL CSessionEditorDoc::OnOpenDocument(LPCTSTR lpszPathName) { }

則在前面調用CWinApp::OpenDocumentFile(szPath)之後,會接著調用OnOpenDocument.(MFC中很多地方就是這樣封裝起來的啊,所以你看著定義了一函數,但不知道是在哪兒被調用的,那就叫一個鬱悶憋屈啊).

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.