您好,登錄后才能下訂單哦!
//**********************// 類類型 class B{ public: int m_num; B():m_num(50){} }; void foo(void) { const B* b1 = new B(); B* b2 = const_cast<B*>(b1); b2->m_num = 200; cout <<"b1:" << b1->m_num << endl;//200 cout <<"b2:" << b2->m_num << endl;//200 const B b3; B b4 = const_cast<B&>(b3); b4.m_num = 300; cout << "b3:" << b3.m_num << endl;//50 cout << "b4:" << b4.m_num << endl;//300 } //************************//
//************************// 基本類型 void foo(){ const int a = 100; int* p1 = const_cast<int*>(&a); *p1 = 200; cout << *p1 << endl;//200 cout << a << endl;//100 const int* p2 = new int(100); int* p3 = const_cast<int*>(p2); *p3 = 200; cout << *p2 << endl;//200 cout << *p3 << endl;//200 } //************************//
你會發現:
A:可以為基本類型或者類類型;
const A a;隨便怎么修改a都不會變化
const A* p = new A();去掉p的const屬性后,*p就變化了.
//*****************// class A{ public: A(){ m_num=1; } int m_num; }; void foo (void){ A a; const A &r = a; A a1 = const_cast<A&>(a); a1.m_num = 200; cout << a1.m_num << endl;//200 cout << a.m_num << endl;//1 } //****************//
const_cast<type-id>(expression)中,type-id只能為指針或引用,其他的都錯,這個表達式即可以去除
expression中的const屬性或volatil屬性,還能增加const屬性或者volatil屬性
const int i = 10;
int i1 = const_cast<int>(i) //錯誤
增加const屬性與volatil屬性相反.
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。