c++ const_cast;
#include<iostream>
using namespace std;
int main()
{
//c++ const_cast;
const int a = 10 ;
int* pA = &a;
}
不能讲一个常量直接赋值给一个int 类型
demo1.cpp: In function ‘int main()’:
demo1.cpp:7:11: error: invalid conversion from ‘const int*’ to ‘int*’ [-fpermissive]
int* pA = &a;
#include<iostream>
using namespace std;
int main()
{
//c++ const_cast;
const int a = 10 ;
//int* pA = &a;
int* pA = const_cast<int*>(&a);
}
编译通过,comst_cast 去除对象的const属性
c++ reinterpret_cast (危险–没有检查)
重新解释类型,既不检查指向的内容,也不检查指针类型本身;但要求转换前后的类型所占内存大小一致,否则会发生编译错误。
#include<iostream>
using namespace std;
int Test()
{
return 0;
}
int main()
{
//c++ const_cast;
const int a = 10 ;
//int* pA = &a;
int* pA = const_cast<int*>(&a);
*pA = 100;
//c++ reinterpret_cast
typedef void(*FuncPtr)();//返回值void 参数为空
FuncPtr funcPtr;
fubcPtr = &Test;
}
报错
demo1.cpp: In function ‘int main()’:
demo1.cpp:17:1: error: ‘fubcPtr’ was not declared in this scope
fubcPtr = &Test;
^~~~~~~
demo1.cpp:17:1: note: suggested alternative: ‘funcPtr’
fubcPtr = &Test;
^~~~~~~
funcPtr
编译通过
#include<iostream>
using namespace std;
int Test()
{
return 0;
}
int main()
{
//c++ const_cast;
const int a = 10 ;
//int* pA = &a;
int* pA = const_cast<int*>(&a);
*pA = 100;
//c++ reinterpret_cast
typedef void(*FuncPtr)();//返回值void 参数为空
FuncPtr funcPtr;
//fubcPtr = &Test;
funcPtr = reinterpret_cast<FuncPtr> (&Test);
}
将Test类型转换为FuncPtr类型
static_cast
拥有与c语言相同的威力和意义,以及相同的限制。他不能将int转为struct,也不能将double转为pointer;这些都是c语言不能完成的,static_cast 不能移除表达式的常量性,因为有const_cast;(来源more effective c++)
用于基本类型转换, 有继承关系对象和指针之间转换,由程序员来确保转换是安全的,他不会产生动态转换的类型安全检查的开销
为了弥补检查问题 dynamic_cast:
只能用于含有虚函数的类, 必须用在多态体系中, 用于类层次间的向上和向下转化;向下时, 如果是非法的对于指针返回NULL.
#include<iostream>
using namespace std;
int Test()
{
return 0;
}
class Base
{
public:
Base():_i(0){;}
virtual void T()
{cout << "Base: T" << _i << endl;}
private:
int _i;
};
class Derived:public Base
{
public:
Derived():_j(1){;}
virtual void T()
{cout << "Derived: T" << _j << endl;}
private:
int _j;
};
int main()
{
//c++ const_cast;
const int a = 10 ;
//int* pA = &a;
int* pA = const_cast<int*>(&a);
*pA = 100;
//c++ reinterpret_cast
typedef void(*FuncPtr)();//返回值void 参数为空
FuncPtr funcPtr;
//fubcPtr = &Test;
funcPtr = reinterpret_cast<FuncPtr> (&Test);
//static_cast 与 dynamic_cast
int ii = 5;
double dd = static_cast<double>(ii);
double dd2 = 5.6;
int ii2 = static_cast<int> (dd2);
Base cb;
Derived cd;
Base* pcb;
Derived* pcd;
//测试子类-》父类
pcb = static_cast<Base*> (&cd);
pcb = dynamic_cast<Base*>(&cd);
if(pcb == NULL)
{
cout << "unsafe dynamic_cast Drerived to Base" << endl;
}
//父类-》子类
pcd = static_cast<Derived*> (&cb);
pcd = dynamic_cast<Derived*>(&cb);
if(pcd == NULL)
{
cout << "unsafe dynamic_cast Base to derived" << endl;
}
}
ls@ls-vpc:~/c++/yichang$ ./a.out
unsafe dynamic_cast Base to derived
可以看出当自上而下出现错误时异常可以被检查