强制类型转换(const_cast)

[1] const_cast的作用

一、常量指针被转化成非常量指针,并且仍然指向原来的对象;
二、常量引用被转换成非常量引用,并且仍然指向原来的对象;
三、常量对象被转换成非常量对象。 

[2] 实例代码

代码如下:

强制类型转换(const_cast)
 1 #include <iostream>

 2 using  namespace std;

 3 

 4 const int xx = 50;

 5 class A

 6 {

 7 public:

 8     int m_nNum;

 9 public:

10     A(int nValue = 100);

11 };

12 

13 A::A(int nValue):m_nNum(nValue)

14 {

15 }

16 

17 void TestFun()

18 {

19     // 第一种情况

20     const A *pA = new A(200);

21     // pA->m_nNum = 100; // compile error !

22     A* pAA = const_cast<A*>(pA);

23     pAA->m_nNum = 199;

24     cout<<pA->m_nNum<<endl;//199

25     // 第二种情况

26     A *pB = new A();

27     pA = pB; // 思考这个原因。为什么这样子可以呢?且看下面的分析:

28     A* const pC = new A(1);

29     A *pD = new A(2); 

30     // pC = pD; // compile error !

31     A*& pE = const_cast<A*>(pC);

32     pE = pD;

33     cout<<pC->m_nNum<<endl;  //2

34     // 第三种情况

35     const A a;

36     // a.m_nNum = 101; //compile error !

37     A b = const_cast<A&>(a);

38     b.m_nNum = 101;

39     cout<<a.m_nNum <<endl; //100

40     cout<<b.m_nNum <<endl; //101

41     // 第四种情况

42     const A c;

43     // c.m_nNum = 101; //compile error !

44     A& d = const_cast<A&>(c);

45     d.m_nNum = 102;

46     cout<<c.m_nNum <<endl; //102

47     cout<<d.m_nNum <<endl; //102

48     // 第五种情况

49     const A e;

50     // e.m_nNum = 103; //compile error !

51     A* pe = const_cast<A*>(&e);

52     pe->m_nNum = 103;

53     cout<<e.m_nNum <<endl; //103

54     cout<<pe->m_nNum <<endl; //103

55     // 第六种情况

56     const int xx = 50;

57     int* yy = const_cast<int *>(&xx);

58     *yy = 200;

59     cout <<xx<<endl; // 50

60     cout <<*yy<<endl; // 200

61     int aa = xx;

62     cout << aa << endl;

63     // 第七种情况

64     const int xxx = 50;

65     int yyy = const_cast<int&>(xxx);

66     yyy = 51;

67     cout << xxx << endl; // 50

68     cout << yyy << endl; // 51

69     // 第八种情况

70     const int xxx2 = 50;

71     int& yyy2 = const_cast<int&>(xxx2);

72     yyy2 = 52;

73     cout << xxx2 << endl; // 50

74     cout << yyy2 << endl; // 52

75 }

76 

77 void main()

78 {

79     TestFun();

80 }
View Code

 

Good  Good  Study, Day  Day  Up.

顺序   选择   循环   总结

你可能感兴趣的:(Const)