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");
}*/