语法,
const_cast<type_name>(expression)
type_name是转换的类型,expression是被转换的对象或者表达式;
const_case有两个功能,分别是去掉const和加上const,更多用于去掉const,修改被const修饰为常量的值;
先简单程序看一下,
void CMybaseView::OnDraw(CDC* pDC)
{
CMybaseDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
CString str1;
int* p1 = new int(202);
const int* p2 = const_cast<const int*>(p1); // 转换为常量指针
*p1 = 303;
//*p2 = 404; // 不能修改
str1.Format("%d", *p1);
pDC->TextOut(30, 30, str1);
str1.Format("%d", *p2);
pDC->TextOut(30, 60, str1);
str1.Format("%p", p1);
pDC->TextOut(30, 90, str1);
str1.Format("%p", p2);
pDC->TextOut(30, 120, str1);
}
//*p2 = 404; 这句不注释掉将引起错误,
error C2166: l-value specifies const object;