const_cast

/*
用法: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 自定义类的成员变量,但是对于内置数据类型,却表现未定义行为
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值