MFC应用程序中指针的使用
作者:gouguijia
CYouSDIDoc *pDoc=GetDocument();一个视只能有一个文档。
CMainFrame *pMain =(CMainFrame *)AfxGetMainWnd();
CMainFrame *pMain=(CmaimFrame *)AfxGetApp()->m_pMainWnd;
CMainFrame *pMain=(CmaimFrame *)AfxGetApp()->m_pMainWnd; CyouView *pView=(CyouView *)pMain->GetActiveView();
CDocument * pCurrentDoc =(CFrameWnd *)m_pMainWnd->GetActiveDocument();
CStatusBar * pStatusBar=(CStatusBar *)AfxGetMainWnd()->GetDescendantWindow(AFX_IDW_STATUS_BAR); CToolBar * pToolBar=(CtoolBar *)AfxGetMainWnd()->GetDescendantWindow(AFX_IDW_TOOLBAR);
(CMainFrame *)GetParent()->m_wndToolBar; (CMainFrame *)GetParent()->m_wndStatusBar;
CMenu *pMenu=m_pMainWnd->GetMenu();
virtual POSITION GetFirstViewPosition() const; virtual CView* GetNextView(POSITION& rPosition) const;注意:GetNextView()括号中的参数用的是引用方式,因此执行后值可能改变。
CTestView* pTestView; POSITION pos=GetFirstViewPosition(); pTestView=GetNextView(pos);这样,便可到了CTestView类的指针pTestView.执行完几句后,变量pos=NULL,因为没有下一个视图类,自然也没有下一个视图类的POSITION.但是这几条语句太简单,不具有太强的通用性和安全特征;当象前面说的那样,当要在多个视图为中返回某个指定类的指针时,我们需要遍历所有视图类,直到找到指定类为止。判断一个类指针指向的是否某个类的实例时,可用IsKindOf()成员函数时行检查,如:
pView->IsKindOf(RUNTIME_CLASS(CTestView));即可检查pView所指是否是CTestView类。
CView* CTestDoc::GetView(CRuntimeClass* pClass) { CView* pView; POSITION pos=GetFirstViewPosition(); while(pos!=NULL){ pView=GetNextView(pos); if(!pView->IsKindOf(pClass)) break; } if(!pView->IsKindOf(pClass)){ AfxMessageBox("Connt Locate the View.\r\n http://www.VCKBASE.com"); return NULL; } return pView; }
CTestView* pTestView=(CTestView*)GetView(RUNTIME_CLASS(CTestView));RUNTIME_CLASS是一个宏,可以简单地理解它的作用:将类的名字转化为CRuntimeClass为指针。
CView* CTestAView::GetView(CRuntimeClass* pClass) { CTestDoc* pDoc=(CTestDoc*)GetDocument(); CView* pView; POSITION pos=pDoc->GetFirstViewPosition(); while(pos!=NULL){ pView=pDoc->GetNextView(pos); if(!pView->IsKindOf(pClass)) break; } if(!pView->IsKindOf(pClass)){ AfxMessageBox("Connt Locate the View."); return NULL; } return pView; }这个函数和2中的GetView()相比,一是多了第一句以取得文档类指针,二是在GetFirstViewPosition()和GetNextView()前加上了文档类指针,以表示它们是文档类成员函数。
CTestBView* pTestbView=(CTestView*)GetView(RUNTIME_CLASS(CTestBView));
POSITION GetFirstDocTemplate( ) const; CDocTemplate *GetNextDocTemplate( POSITION & pos ) const;第二个函数返回由pos 标识的文档模板。POSITION是MFC定义的一个用于迭代或对象指针检索的值。通过这两个函数,应用程序可以遍历整个文档模板列表。如果被检索的文档模板是模板列表中的最后一个,则pos参数被置为NULL。
viaual POSITION GetFirstDocPosition( ) const = 0; visual CDocument *GetNextDoc(POSITION & rPos) const = 0;如果列表为空,则rPos被置为NULL.
CDocTemplate * GetDocTemplate ( ) const;如果该文档不属于文档模板管理,则返回值为NULL。
Virtual POSITION GetFirstViewPosition( ) const; Virtual CView * GetNextView( POSITION &rPosition) cosnt;应用程序可以调用CDocument::GetFirstViewPosition返回与调用文档相联系的视的列表中的第一个视的位置,并调用CDocument::GetNextView返回指定位置的视,并将rPositon的值置为列表中下一个视的POSITION值。如果找到的视为列表中的最后一个视,则将rPosition置为NULL.
文章评论(0条评论)
登录后参与讨论