现在的位置: 首页 > 综合 > 正文

const_cast

2014年02月28日 ⁄ 综合 ⁄ 共 1498字 ⁄ 字号 评论关闭
/*
用法: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:

b1: 200
b2: 200

b3: 50
b4: 200

b5: 200
b6: 200

x: 50 address: 002CF880
*y: 200 address: 002CF880

xx: 50 address: 002CF884
*yy: 200 address: 002CF884

xxx: 50 address: 002CF88C
yyy: 200 address: 002CF888

可以改变const 自定义类的成员变量,但是对于内置数据类型,却表现未定义行为

抱歉!评论已关闭.