空型铸造到类型

Void cast to type

本文关键字:类型 空型      更新时间:2023-10-16

我有基于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 *'    

阅读本文。由于->运算符的优先级(2)高于强制转换运算符的优先级

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

为了避免这种情况,应该在强制转换时使用括号。

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