分类: C/C++
2008-12-16 08:54:29
该运算符用来强制消除对象的const、 volatile和__unaligned attribute等属性。被const_cast修饰的对象:
常量指针被转化成非常量指针,并且仍然指向原来的对象;
常量引用被转换成非常量引用,并且仍然指向原来的对象;
常量对象被转换成非常量对象。
举一个用法的例子:
class CCTest {
public:
void setNumber(
int
);
void printNumber() const;
private:
int number;
};
void
CCTest::setNumber( int num )
{ number =
num; }
void
CCTest::printNumber() const {
cout<<"Before change: "<
const_cast
//l-value specifies const
object
cout<<"After change: "<<
number<
}
void main() {
CCTest X;
X.setNumber( 8 );
X.printNumber();
}
输出:
Before change: 8
After change: 7
用法例子2:
class B{
public:
B(int
a){m_iNum = a;}
int
m_iNum;
};
void main() {
const
B *pB = new B(10);
//pB->m_iNum
= 100; //编译错误:l-value specifies const object
cout<
const_cast(pB)->m_iNum
= 200; //OK,去const转换后,可以正常修改
cout<
}
输出:
10
200