static_cast
- 普通类型转换 int->float
- pointer to void*, void* to pointer
- 向上类型转换不是必须的, 但是向下转换只要不是虚拟继承就能使用
dynamic_cast
只用来处理多态下的指针和引用
class Animal |
const_cast
可以用来对变量移除和添加const, 其他的cast都无法做到 (static_cast可以添加const但是不能去除)
将const变量移除const是未定义的, 将非const的变量
的const引用
是安全的
int a = 1; |
ex1.将const成员函数的this指针去除const来修改成员变量
// https://www.geeksforgeeks.org/const_cast-in-c-type-casting-operators/
using namespace std;
class student
{
private:
int roll;
public:
// constructor
student(int r):roll(r) {}
// A const function that changes roll with the help of const_cast
void fun() const
{
( const_cast <student*> (this) )->roll = 5;
}
int getRoll() { return roll; }
};
int main(void)
{
student s(3);
cout << "Old roll number: " << s.getRoll() << endl;
s.fun();
cout << "New roll number: " << s.getRoll() << endl;
return 0;
}
//$ Old roll number: 3
//$ New roll number: 5ex2.去除参数的const, 来调用非const参数的函数
using namespace std;
int fun(int* ptr)
{
return (*ptr + 10);
}
int main(void)
{
const int val = 10;
const int *ptr = &val;
int *ptr1 = const_cast <int *>(ptr);
cout << fun(ptr1);
return 0;
}
//$ 20
reinterpret_cast
typedef unsigned short uint16; |
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。