c++ 常用的类型转化修饰关键字:
static_cast (用于一般的类型转化,double 转成 int 等)
const_cast (这个用于 const 修饰过的字符数组,转型是为了去常量)
dynamic_cast(用于子类和父类之间的转型)
#include <stdlib.h>
#include <iostream>
using namespace std;
void* func(int type){
switch (type){
case 1:{
int i = 3;
return &i;
}
break;
case 2:{
char a = 'A';
return &a;
}
break;
}
}
void fun(const char c[]){
//c[1] = 'a';
//这次转型是为了去常量,下面是c 的写法,这种写法可读性不高
//char* c_p = (char*)c;
//c_p[1] = 'a';
char* c_p = const_cast<char*>(c);
c_p[1] = 'a';
cout << c << endl;
}
/*
void main(){
//int i = 8;
//double a = 9.5;
//i = static_cast<int>(a);
//printf("%d\n", i);
//cout << i << endl;
//这种写法是c++ 中
//char* a = static_cast<char*>(func(2));
//cout << *a << endl;
//c 中写法
//char* b = (char*)(func(2));
//cout << *b << endl;
char c[] = "hello";
fun(c);
system("pause");
}*/
class Person{
public:
virtual void print(){
cout << "人" << endl;
}
};
class Man : public Person{
public:
void print(){
cout << "男人" << endl;
}
void chasing(){
cout << "泡妞" << endl;
}
};
class Woman : public Person{
public:
virtual void print(){
cout << "女人" << endl;
}
void createBaby(){
cout << "生孩子" << endl;
}
};
void fun1(Person* p){
p->print();
//不管转型是否成功都会调用泡妞的方法
//Man * m = (Man*)p;
//m->chasing();
//转型不成功就会返回NULL;作为一个判断标准,dynamic_cast 关键字用于子类和父类之间的上下转型
Man * m = dynamic_cast<Man*>(p);
if (m != NULL){
m->chasing();
cout << m << endl;
}
else{
Woman* w = dynamic_cast<Woman*>(p);
w->createBaby();
}
}
/*
void main(){
Woman w;
//实际类型是女人,要想调用女人的方法必须加virtual 关键字
Person *p = &w;
fun1(p);
system("pause");
}*/