简体   繁体   中英

Void cast to type

I have MFC dialog based application.

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

}

Line this->SetWindowTextW(L"bla"); changes form caption to bla

I expect line (CThr_MfcDlg*)GetDlgItem(IDD_THR_MFC_DIALOG)->SetWindowText(L"hello") ; should change caption to hello , but have compile error:

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

Read this . Since -> operator's precedence (2) is higher than cast operator's (3), your code is parsed in this way:

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

To avoid this, you should use parenthesis with casting.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM