const_cast 运算符
从类中移除 const、volatile 和 __unaligned 特性。
语法
const_cast < type-id > ( expression )
备注
指向任何对象类型的指针或指向数据成员的指针可显式转换为完全相同的类型(const、volatile 和 __unaligned 限定符除外)。对于指针和引用,结果将引用原始对象。对于指向数据成员的指针,结果将引用与指向数据成员的原始(未强制转换)的指针相同的成员。根据引用对象的类型,通过生成的指针、引用或指向数据成员的指针的写入操作可能产生未定义的行为。
您不能使用 const_cast 运算符直接重写常量变量的常量状态。
const_cast 运算符将 null 指针值转换为目标类型的 null 指针值。
// expre_const_cast_Operator.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
class CCTest {
public:
void setNumber( int );
void printNumber() const;
private:
int number;
};
void CCTest::setNumber( int num ) { number = num; }
void CCTest::printNumber() const {
cout << "\nBefore: " << number;
const_cast< CCTest * >( this )->number--;
cout << "\nAfter: " << number;
}
int main() {
CCTest X;
X.setNumber( 8 );
X.printNumber();
}
在包含 const_cast 的行中,this 指针的数据类型为 const CCTest *。 const_cast 运算符会将 this 指针的数据类型更改为 CCTest *,以允许修改成员 number。强制转换仅对其所在的语句中的其余部分持续。
reinterpret_cast 运算符
允许将任何指针转换为任何其他指针类型。也允许将任何整数类型转换为任何指针类型以及反向转换。
语法
reinterpret_cast < type-id > ( expression )
备注
#include <iostream>
using namespace std;
// Returns a hash code based on an address
unsigned short Hash( void *p ) {
unsigned int val = reinterpret_cast<unsigned int>( p );
return ( unsigned short )( val ^ (val >> 16));
}
using namespace std;
int main() {
int a[20];
for ( int i = 0; i < 20; i++ )
cout << Hash( a + i ) << endl;
}
Output:
64641 64645 64889 64893 64881 64885 64873 64877 64865 64869 64857 64861 64849 64853 64841 64845 64833 64837 64825 64829
reinterpret_cast 允许将指针视为整数类型。结果随后将按位移位并与自身进行“异或”运算以生成唯一的索引(具有唯一性的概率非常高)。该索引随后被标准 C 样式强制转换截断为函数的返回类型。