const_cast
2402 ワード
/*
:const_cast<type_id> (expression)
const volatile 。 const volatile , type_id expression 。
、 , ;
、 , ;
、 。
type_id
*/
class B
{
public:
int m_iNum;
B():m_iNum(50) {}
};
void foo()
{
const B *b1 = new B();
//b1->m_iNum = 100; //compile error
B *b2 = const_cast<B*>(b1);
b2->m_iNum = 200;
cout<<"b1: "<< b1->m_iNum <<endl;
cout<<"b2: "<< b2->m_iNum <<endl;
cout<<endl;
const B b3;
//b3.m_iNum = 100; //compile error
B b4 = const_cast<B&>(b3);//b4 is another object
b4.m_iNum = 200;
cout<<"b3: "<<b3.m_iNum <<endl;
cout<<"b4: "<<b4.m_iNum <<endl;
cout<<endl;
const B b5;
//b5.m_iNum = 100; //compile error
B &b6 = const_cast<B&>(b5);
b6.m_iNum = 200;
cout<<"b5: "<<b5.m_iNum <<endl;
cout<<"b6: "<<b6.m_iNum <<endl;
cout << endl;
// force to convert
const int x = 50;
int* y = (int *)(&x);// same address, but the content is different
*y = 200;
cout << "x: "<<x<<" address: "<<&x<<endl;
cout << "*y: "<<*y<<" address: "<<y<<endl;
cout<<endl;
// int
const int xx = 50;
int* yy = const_cast<int *> (&xx);// same address, but the content is different
*yy = 200;
cout << "xx: "<<xx<<" address: "<<&xx<<endl;
cout << "*yy: "<<*yy<<" address: "<<yy<<endl;
cout<<endl;
// int
const int xxx = 50;
int yyy = const_cast<int&> (xxx);// another int
yyy = 200;
cout << "xxx: "<<xxx<<" address: "<<&xxx<<endl;
cout << "yyy: "<<yyy<<" address: "<<&yyy<<endl;
}
int _tmain(int argc, char* argv[])
{
foo();
return 0;
}
result:
b 1:200 b 2:200 b 3:50 b 4:200 b 5:200 b 6:200 x:50 address:002CF 880*y:200 address:002CF 880 xx:50 address:002CF 884*yy:200 address:002CF 884 xxx:50 address:002CF 88 C yy:200 address:002CF 888はconstカスタムクラスのメンバー変数を変更することができるが、内蔵データ型に対しては未定義の挙動を示す