1,const_cast()操作符;
//目标类型只能是指针or引用
#include <iostream>
using namespace std;
int main()
{
const int a = 10;
int *p1 = const_cast<int *>(&a); //去除变量的const属性
//a = 20; //为什么不可以用变量a初始化??
*p1 = 20;
cout << *p1 << endl;
int &p3 = const_cast<int &>(a); //引用与指针一样
//int &p4 = 1; //用常量初始化普通引用无效
const int &p5 = 2; //用常量初始化常引用
cout << p5 << endl;
return 0;
}
2 static_cast()操作符;
#include <iostream>
using namespace std;
class Parent
{
public:
Parent()
{
cout << "Parent构造函数" << endl;
}
void show()
{
cout << "Parent show" << endl;
}
};
class Child : public Parent
{
public:
Child()
{
cout << "Child构造函数" << endl;
}
void print()
{
cout << "Child print" << endl;
}
};
int main()
{
int a = 1;
float b = 5.23;
a = (int)b; //c语言转换方式
cout << "c语言转换方式的a=" << a << endl;
int *p;
a = static_cast<int>(b); //用于基本类型间转换
cout << a << endl;
//p = static_cast<int *>(&b); //不能用于基本类型间指针转换
Parent par;
Child ch;
par.show();
ch.print();
par = static_cast<Parent>(ch); //用于有继承关系的类之间对象的转换
cout << "*****************" << endl;
ch.show();
cout << "==================" << endl;
//Parent *pa = static_cast<Parent *>(new Child); //用于有继承关系的类指针之间转换 (虽然可以,但是写成这样没有对象 无法调用成员函数,看起来效果不明显,下边的可以)
Parent *p1;
Child *c1;
p1 = static_cast<Parent *>(c1);
c1->show();
return 0;
}
3 dynmic_cast操作符;
//dynmic_cast操作符会在运行期间对可疑的转换类型操作进行安全检查,而static_cast不会进行安全检查
#include <iostream>
using namespace std;
class Parent
{
public:
virtual void show()
{
cout << "Parent show" << endl;
}
};
class Child : public Parent
{
public:
void show()
{
cout << "Child show" << endl;
}
};
int main()
{
Parent *p1 = new Parent[10];
Child *c1 = new Child[10];
p1 = c1; //向上转型 派生类指针初始化基类指针(多态中 基类指针本来就可以指向派生类对象)
p1->show();
c1 = dynamic_cast<Child *>(p1); //向下转型 (隐式转换)
c1->show(); //此时c1为基类指针 因为多态原因 它的输出还是派生类的show
return 0;
}
4 reinterpret_cast操作符;
#include <iostream>
using namespace std;
int main()
{
int *a ;
float b = 1.23;
//a = &b; //引用不能用于不同类型之间(必须同是int or 同是float类型)
//cout << *a << endl;
a = reinterpret_cast<int *>(&b); //可以用于普通类型间指针的转换,但不安全
cout << *a << endl; //编译没问题,但打印的结果不是1
a = reinterpret_cast<int *>(0x100); //用于整数和指针间的转换
return 0;
}
总结:
(1)const_cast()操作符;
1,取消const属性。
2,可以用常量初始化常引用,但不能用常量初始化普通引用。
(2)static_cast()操作符;
1,可用于基本类型间转换,例如 int = float,但不能用于基本类型指针间转换。
2,可用于有继承关系的类之间对象间(父类对象和子类对象)的转换 和 指针之间(父类指针和子类指针)的转换。
(3)dynmic_cast()操作符;
用于有继承关系的基类与派生类指针之间的转换,前提是必须有多态存在。
1,向上转型 基类指针对象 = 派生类指针对象 ;
2,向下转型 派生类指针对象 = 基类指针对象;
(4)reinterpret_cast()操作符;
1,可用于普通类型之间的转换(但不安全);
2,可用于整数和指针之间的转换。