const_cast 列子

#include <iostream>

int main(int argc, char **argv)
{
		const int* pA = new int(3);
		int& iB = const_cast<int&>(*pA); //pA的值可以改变
		int* pC = const_cast<int*>(pA);
		iB = 5;
		*pC = 6;
		std::cout << "a=" << *pA << std::endl;
		std::cout << "b=" << iB << std::endl;
		std::cout << "c=" << *pC << std::endl;
		std::cout << "pA=" << pA << std::endl;
		std::cout << "pB=" << &iB << std::endl;
		std::cout << "pC=" << pC << std::endl;
		delete pA;

		std::cout << "\nComparison:\n"  << std::endl;

		const int iA= 789 ;
		iB = const_cast<int&>(iA);//另外申请一块空间,副本
		pC = const_cast<int*>(&iA);
		iB = 987;
		*pC = 999;
		std::cout << "a=" << iA << std::endl;
		std::cout << "b=" << iB << std::endl;
		std::cout << "c=" << *pC << std::endl;
		std::cout << "pA=" << &iA << std::endl;
		std::cout << "pB=" << &iB << std::endl;
		std::cout << "pC=" << pC << std::endl;

		return 0;
}

 

posted @ 2013-11-03 18:45  forgood  阅读(157)  评论(0编辑  收藏  举报