一、static_cast
相关类型转换:
double f = 13.14f;
int i = static_cast<int> f;
父类转子类:
子类* p2 = static_cast<父类*>(p);
二、const_cast
不能去除常量的常量性:
const int i = 100;
int i = const_cast<int> i;//这是不行的,不是指针和引用
去除引用的常量性:
int k = 1;
const int & j = k;
int &qq = const_cast<int &>(j);
qq = 2;
cout << k << endl; //输出为2
去除指针的常量性:
int k = 1;
const int * j = &k;
int * qq = const_cast<int *>(j);
*qq = 2;
cout << k << endl;//输出为2
去除类的常量性:
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;
}
在const成员函数中不能修改成员变量。const成员函数中this 指针的数据类型为 const CCTest *,通过const_cast改变为CCTest *,这样就可以改变类的成员函数了。
三、dynamic_cast
class Human {
virtual void talk();
};
class WoMen : public Human {
void talk();
};
int main()
{
Human *human = new WoMen();
WoMen *pMen = dynamic_cast<WoMen*>(human);
if (pMen != nullptr)
{
cout << "find" << endl;
}
else
{
cout << "not find" << endl;
}
}
dynamic_cast转换的类型必须有virtual方法。
四、reinterpret_cast
将操作数的一种类型转换为另一种类型。
int i = 10;
int *pi = &i;
char * pvoid = reinterpret_cast<char *>(pi);
本文详细介绍了C++中的四种类型转换:static_cast、const_cast、dynamic_cast和reinterpret_cast的使用方法及注意事项。从基本语法到具体应用案例,帮助读者深入理解这些转换方式的工作原理。
344

被折叠的 条评论
为什么被折叠?



