static_cast
// dynamic_cast
reinterpret_cast
const_cast
static_cast:对于隐式类型可以转化的,即可以使用此类型。
float a = 5.6;
int b = 5;
b = static_cast<int>(a);
a = static_cast<float>(b); //C++ 不要随意发生强转
void *p; int *q;
p = q; // void * 可以接受任何类型的指针
// q = p; //[ERROR]
q = static_cast<int*>(p);
int x = 10;
int y = 3;
float z = static_cast<float>(x)/y;
char *pc = static_cast<char*>malloc(100);
reinterpret_cast:双方隐式转换都通不过的时候使用
char *p; int *q;
p = reinterpret_cast<char*>(q);
int a[5] = {1, 2, 3, 4, 5};
int *p = reinterpret_cast<int*>(reinterpret_cast<int>(a)+1);
const_cast:脱常,只能引用于指针和引用
//const 修饰的东西一定不能改
void func(const int & v)// const 对引用的拓展,引用只能够传递变量,而不能传递常量
{
//不能修改v内的内容;
}
int main()
{
const int a = 19;
func(a + 10);
}
void func2(int & v)
{
}
int main()
{
const int a = 19;
func2(a); //[ERROR] const int不能传递给一个int类型的变量
}
void func2(int & v)
{
}
int main()
{
const int a = 19;
func2(const_cast<int&>(a)); //[ERROR] const int不能传递给一个int类型的变量
int & ra = const_cast<int&>(a);
ra = 200;
cout<<"a = "<<a<<endl;
cout<<"ra = "<<ra<<endl; //ra的值修改了,但是a的值没有修改
// 两者的地址一样
int * pi = const_cast<int*>(&a);
*pi = 200;
cout<<"a = "<<a<<endl;
cout<<"*pi = "<<*pi<<endl; // *pi的值修改了,但是a的值没有修改
// 两者的地址一样
}
struct A
{
int data;
};
const A ad = {10};
A * pA = const_cast<A*>(&ad);
pA->data = 200;
cout<<pA->data<<endl; // 输出200
上面的这些代码虽然是看似可以修改const变量引用或指针的值,但是:
妄图对const_cast指针、引用等的修改行为都是未定义的。
换句话说就是,可以改变const自定义类的成员变量,但是对于内置数据类型,却表现未定义行为。
Depending on the type of the referenced object, a write operation through the resulting pointer, reference, or pointer to data member might produce undefined behavior.
宏在预处理的时候发生了替换
const在编译的阶段发生了替换