1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
//**********************//
类类型
class
B{
public
:
int
m_num;
B():m_num(50){}
};
void
foo(
void
) {
const
B* b1 =
new
B();
B* b2 =
const_cast
<B*>(b1);
b2->m_num = 200;
cout <<
"b1:"
<< b1->m_num << endl;
//200
cout <<
"b2:"
<< b2->m_num << endl;
//200
const
B b3;
B b4 =
const_cast
<B&>(b3);
b4.m_num = 300;
cout <<
"b3:"
<< b3.m_num << endl;
//50
cout <<
"b4:"
<< b4.m_num << endl;
//300
}
//************************//
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
//************************//
基本类型
void
foo(){
const
int
a = 100;
int
* p1 =
const_cast
<
int
*>(&a);
*p1 = 200;
cout << *p1 << endl;
//200
cout << a << endl;
//100
const
int
* p2 =
new
int
(100);
int
* p3 =
const_cast
<
int
*>(p2);
*p3 = 200;
cout << *p2 << endl;
//200
cout << *p3 << endl;
//200
}
//************************//
|
你会发现:
A:可以为基本类型或者类类型;
const A a;随便怎么修改a都不会变化
const A* p = new A();去掉p的const属性后,*p就变化了.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
//*****************//
class
A{
public
:
A(){
m_num=1;
}
int
m_num;
};
void
foo (
void
){
A a;
const
A &r = a;
A a1 =
const_cast
<A&>(a);
a1.m_num = 200;
cout << a1.m_num << endl;
//200
cout << a.m_num << endl;
//1
}
//****************//
|
const_cast<type-id>(expression)中,type-id只能为指针或引用,其他的都错,这个表达式即可以去除
expression中的const属性或volatil属性,还能增加const属性或者volatil属性
const int i = 10;
int i1 = const_cast<int>(i) //错误
增加const属性与volatil属性相反.
本文转自神ge 51CTO博客,原文链接:http://blog.51cto.com/12218412/1867169