2015-09-23 65 views
0

我有一個派生自CDialog(CNotificationDialog)的類,它是在Visual Studio選擇添加類選項時自動生成的。OnInitDialog沒有在CDialog的後代中調用

我也有另一個派生自CNotificationDialog(CWebNotificationDialog)的類。

我的代碼是這樣的:

CNotificationDialog* dlg = new CWebNotificationDialog(); 
dlg->Display(); 

將顯示對話框,但CWebNotificationDialog :: OnInitDialog中的方法不被調用。只調用CNotificationDialog :: OnInitDialog方法。

在你問之前,是的,它被宣佈爲虛擬。 我已經嘗試添加DECLARE_DYNAMIC,BEGIN_MESSAGE_MAP和所有其他自動生成的宏,但沒有運氣。

我在做什麼錯?

這是CNotificationDialog :: OnInitDialog的外觀。

BOOL C1NotificationDialog::OnInitDialog() 
{ 
    CDialog::OnInitDialog(); 

    HICON hIconBig = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_ICON, 32, 32, LR_SHARED); 
    CStatic *pPictureCtrl = (CStatic*)GetDlgItem(IDS_NOTIFICATION_DLG_LOGO); 
    pPictureCtrl->SetIcon(hIconBig); 

    return TRUE; 
} 

它的聲明如下:

protected: 
virtual BOOL OnInitDialog(); 
+1

你做錯了。你應該使用基類指針,這是一個常用的scernario。我不知道你爲什麼使用基類對象的派生類指針,聽起來很腥。 – zar

+0

沒有CDialog :: Display –

+0

Yest,這是必要的。發佈CNotificationDialog的OnInitDialog。 – rrirower

回答

1

我只是有這個同樣的問題,當時很困惑,發現在我的情況,這個問題是這樣的:

如果您呼叫的成員函數的Create()函數在類構造函數中,按照MSDN中的建議,它必須放在派生類的構造函數中。呼叫從一個基礎類構建內的虛擬功能是要避免的,每一個問題:

Calling virtual functions inside constructors

我發現,在下面的代碼,派生類的OnInitDialog()沒有被調用時的一個目的派生類被實例化:

class BaseDialog : public CDialog{ 
public: 
    BaseDialog(UINT resourceID, CWnd *pParent) : CDialog(resourceID, pParent){ 
     Create(resourceID, pParent); 
    }; 
}; 

class DerivedDialog : public BaseDialog{ 
public: 
    DerivedDialog(UINT resourceID, CWnd *pParent) : BaseDialog(resourceID, pParent){}; 

    BOOL OnInitDialog(){ /* NOT CALLED */}; 
}; 

使用create()從派生的類的構造函數被調用,派生類的OnInitDialog()被調用作爲意圖:

class BaseDialog : public CDialog{ 
public: 
    BaseDialog(UINT resourceID, CWnd *pParent) : CDialog(resourceID, pParent){ 
     // Create(resourceID, pParent); 
    }; 
}; 

class DerivedDialog : public BaseDialog{ 
public: 
    DerivedDialog(UINT resourceID, CWnd *pParent) : BaseDialog(resourceID, pParent){ 
     Create(resourceID, pParent); 
    }; 

    BOOL OnInitDialog(){ /* This was called */ }; 
}; 
0

你調用基類的CDialog和從CWebNotificationDialog派生的OnInitDialog。試試...

BOOL C1NotificationDialog::OnInitDialog() 
{ 
    CWebNotificationDialog::OnInitDialog(); 
+0

我不明白。我該怎麼做? – conectionist

+0

@conectionist查看更新後的答案。 – rrirower

+0

這不是它的工作原理。 CWebNotificationDialog派生自CNotificationDialog。 CNotificationDialog不知道它的後代。如果我從C1NotificationDialog派生另一個類,該怎麼辦?那麼C1NotificationDialog :: OnInitDialog()的代碼將如何查看?這個想法是根據dlg指向的內容調用適當的OnInitDialog。這是多態。 – conectionist

相關問題