2014-10-01 62 views
1

我有基於MFC對話框的應用程序。無效鑄型

void CThr_MfcDlg::OnBnClickedButton1() 
{ 
    this->SetWindowTextW(L"bla"); 
    (CThr_MfcDlg*)GetDlgItem(IDD_THR_MFC_DIALOG)->SetWindowText(L"hello") ; 

} 

this->SetWindowTextW(L"bla");改變窗體的標題改爲bla

我希望線(CThr_MfcDlg*)GetDlgItem(IDD_THR_MFC_DIALOG)->SetWindowText(L"hello") ;應該改變標題爲hello,但有編譯錯誤:

Error 1 error C2440: 'type cast' : cannot convert from 'void' to 'CThr_MfcDlg *'  
+0

嘗試'((CThr_MfcDlg *)函數GetDlgItem(IDD_THR_MFC_DIALOG)) - > ...' – 2014-10-01 10:52:52

+5

問自己,爲什麼'(CThr_MfcDlg *)'存在於這個代碼*都*。 ['CWnd :: GetDlgItem'](http://msdn.microsoft.com/en-us/library/77d16yhw.aspx)返回一個'CWnd *',它支持['CWnd :: SetWindowText'](http:///msdn.microsoft.com/en-us/library/yhczy8bz.aspx)。 – WhozCraig 2014-10-01 10:52:58

+1

+1以抵消downvote。我認爲這不是一個壞問題,因爲初學者可以很容易犯這個錯誤。 – ikh 2014-10-01 10:55:25

回答

1

this。自 - >運算符的優先級(2)高於鑄運營商(3),你的代碼被解析這樣:

(CThr_MfcDlg*) (GetDlgItem(IDD_THR_MFC_DIALOG)->SetWindowText(L"hello")) ; 

爲了避免這種情況,你應該使用括號與鑄造。

// this will be correct. 
((CThr_MfcDlg*)GetDlgItem(IDD_THR_MFC_DIALOG))->SetWindowText(L"hello"); 
+0

句法正確,但我不知何故更喜歡WhozCraig的解決方案。 ;-) – DevSolar 2014-10-01 10:58:29

+0

@DevSolar當然。但我認爲我對OP的問題是一個適當的問題。該問題不僅包含'SetWindowText'-ing,而且包含*運算符優先級*,我認爲OP應該知道。 – ikh 2014-10-01 11:00:28