除了能使用c语言的强制类型转换外,还有:转换操作符 (新式转换)
一 可以直接强制类型转换
int i = 8;
double d = 9.5;
i = (int)d;
原始类型转换,所有情况都是一种写法;可读性性不高,没有提示,有转换风险
二 static_cast普通值类型转换
- 基础类型之间互转。如:float转成int、int转成unsigned int等
- 指针与void之间互转。如:float*转成void*、Bean*转成void*、函数指针转成void*等
- 子类指针/引用与 父类指针/引用 转换。
class Parent {
public:
void test() {
cout << "p" << endl;
}
};
class Child :public Parent{
public:
void test() {
cout << "c" << endl;
}
};
Parent *p = new Parent;
Child *c = static_cast<Child*>(p);
//输出c
c->test();
//Parent test加上 virtual 输出 p
三 const_cast 去常量
修改类型的const或volatile属性
void func(const char c[]) {
//c[1] = a;
//去掉const 关键字
char* c_p = const_cast<char *>(c);
c_p[1] = 'X';
}
void main() {
i = static_cast<int>(d);
char c[] = "hello";
cout << "c = " << c << endl;
func(c);
cout << "c = " << c << endl;
system("pause");
}
运行结果:
c = hello
c = hXllo
四 dynamic_cast基类和派生类之间的转换
主要 将基类指针、引用 安全地转为派生类.
在运行期对可疑的转型操作进行安全检查,仅对多态有效
//基类至少有一个虚函数
//对指针转换失败的得到NULL,对引用失败 抛出bad_cast异常
class Person {
public :
virtual void print() {
cout << "Person" << endl;
}
};
class Man :public Person {
public:
void print() {
cout << "Man" << endl;
}
void chasing() {
cout << "chasing" << endl;
}
};
class Woman :public Person {
public:
void print() {
cout << "Man" << endl;
}
void createBaby() {
cout << "createBaby" << endl;
}
};
void funx(Person * obj) {
//Man *m = (Man *)obj;//如果是Woman会有问题
//m->chasing();
Man *m = dynamic_cast<Man*>(obj);
if (m != nullptr) {
m->chasing();
}
else {
cout << " 不是Man的类型" << endl;
}
}
void main() {
Woman *wm = new Woman();
funx(wm);
system("pause");
}
运行结果:不是Man的类型
五 reinterpret_cat 函数指针的转换
对指针、引用进行原始转换
float i = 10;
//&i float指针,指向一个地址,转换为int类型,j就是这个地址
int j = reinterpret_cast<int>(&i);
cout << hex << &i << endl;
cout << hex << j << endl;
cout<<hex<<i<<endl; //输出十六进制数
cout<<oct<<i<<endl; //输出八进制数
cout<<dec<<i<<endl; //输出十进制数
((Void*)p)
不常用的方法,一般在Void *之间
六 char*与int转换
//char* 转int float
int i = atoi("1");
float f = atof("1.1f");
cout << i << endl;
cout << f << endl;
//int 转 char*
char c[10];
//10进制
itoa(100, c,10);
cout << c << endl;
//int 转 char*
char c1[10];
sprintf(c1, "%d", 100);
cout << c1 << endl;