1 静态类型转换和强制类型转换
1 static_cast reinterpret_cast
#include<iostream>
using namespace std;
void main() {
double dpi = 3.1415926;
int num1 = (int)dpi;
int num2 = static_cast<int>(dpi);
int num3 = dpi;
char* p1 = (char *)"hello...itcast";
int* p2 = NULL;
p2 = reinterpret_cast<int*>(p1);
cout << "p1:" << p1 << endl;
cout << "p2:" << p2 << endl;
}
结果
p1:hello...itcast
p2:006D9B30
2 dynamic_cast
动态类型转换,安全的基类和子类之间转换;运行时类型检查
#include<iostream>
using namespace std;
class Tree {};
class Animal {
public:
virtual void cry() = 0;
};
class Dog :public Animal{
public:
void cry() {
cout << "wangwang" << endl;
}
void athome() {
cout << "at home" << endl;
}
};
class Cat :public Animal {
public:
void cry() {
cout << "miaomiao" << endl;
}
void catch_mouse() {
cout << "catch_mouse" << endl;
}
};
void objplay(Animal *base) {
base->cry();
Dog* pdog = dynamic_cast<Dog*>(base);
if (pdog != NULL) {
pdog->athome();
}
Cat* pcat = dynamic_cast<Cat*>(base);
if (pcat != NULL) {
pcat->catch_mouse();
}
}
void main() {
Dog d1;
Cat c1;
Animal* pBase = NULL;
pBase = &d1;
pBase = static_cast<Animal*>(&d1);
pBase = reinterpret_cast<Animal*>(&d1);
{
Tree t1;
pBase = reinterpret_cast<Animal*>(&t1);
}
objplay(&d1);
objplay(&c1);
}
结果
wangwang
at home
miaomiao
catch_mouse
3 const_cast
去除变量只读属性
#include<iostream>
using namespace std;
void printBuf(const char* p) {
char* p1 = NULL;
p1 = const_cast<char*>(p);
p1[0] = 'Z';
cout << p << endl;
}
void main() {
char buf[] = "abdfefadf";
printBuf(buf);
}
结果
Zbdfefadf
一般不建议使用类型转换
|