#include <iostream>
using namespace std;
class Father{
public :
int time;
virtual void run(){
cout<< "Fatner is running" <<endl;
}
};
class Son : public Father{
public:
void run(){
cout << "Son is plating" <<endl;
}
};
void main(){
//静态转换
printf("%d\n",static_cast<int>(10.5));
printf("%f\n",static_cast<float>(20));
//指针类型转换
int* intp = new int(5);
char* charp = reinterpret_cast<char*>(intp);
for(int i = 0; i < 4; i++){
cout<<reinterpret_cast<void*>(charp+i) << static_cast<int>(*(charp+i)) <<endl;
}
//涉及const必须使用const_cast
int num[5] = {1,2,3,4,5};
const int * p = num;
int * pum = const_cast<int*>(p);
/**
Father father;
Son son;
Father* fp;
fp = &father;
fp->run();
fp = &son;
fp->run();*/
Father* father = new Father;
Son* son = new Son;
Father* fp = dynamic_cast<Father*>(son);
fp->run();
Son* sp = dynamic_cast<Son*>(father);
sp->run();
cin.get();
}
基本类型 《-------》类类型
#include <iostream>
using namespace std;
class Myclass{
public:
int x;
int y;
//基本类型 --》 类类型
explicit Myclass(int a) : x(a), y(a){
cout << "myclass()" << endl;
}
//基本类型--》 类类型
void operator = (int num){
cout << "operator = " << endl;
this->x = num;
this->y = num;
}
//类类型 --》 基本类型
operator int(){
return x+y;
}
};
void main(){
Myclass myclass(10);
//explicct 禁止隐式转换 但不能规避显示转换
Myclass myclass2 = static_cast<Myclass>(100);
Myclass myclass3 = Myclass(200);
myclass3 = 200;
int d = myclass3;
cout << d << endl;
cin.get();
}
类类型的数据转换
#include <iostream>
using namespace std;
class TwoPoint{
public:
int x;
int y;
TwoPoint(int a , int b) : x(a) , y(b){
}
};
class ThreePoint{
public:
int x;
int y;
int z;
ThreePoint():x(10),y(20),z(30){
}
ThreePoint(const TwoPoint& teoPoint){
this->x = teoPoint.x;
this->y = teoPoint.y;
this->z = 100;
}
operator TwoPoint(){
return TwoPoint(x,y);
}
void operator = (const TwoPoint& teoPoint){
this->x = teoPoint.x;
this->y = teoPoint.y;
this->z = 100;
}
};
void main(){
TwoPoint two(200,300);
ThreePoint three(two);
cout << three.x << three.y << three.z << endl;
ThreePoint threes;
two = threes;
cout << two.x << two.y << endl;
cout << "Nanjing" << endl;
cin.get();
}
下面就讲一下dynamic_cast使用
dynamic_cast只能识别多态类型的指针和引用 必须要虚函数才能转换
#include <iostream>
using namespace std;
class base{
public:
virtual void show(){
cout << "base show" << endl;
}
};
class baseX :public base{
public:
void show(){
cout << "baseX show" << endl;
}
};
void main(){
//base* p = new baseX;
//p->show();
dynamic_cast只能识别多态类型 必须要虚函数才能转换
//baseX* p1 = dynamic_cast<baseX*>(p); //转换成功 依赖于virtual 没有virtual就不是多态类型
//p1->show();
//base* p = new base;
//base* p1 = new baseX;
多态 父类指针 可以转化为子类指针
//baseX* p2 = dynamic_cast<baseX*>(p1);
//cout << (void*)p2 << endl;
base* p = new base;
base* p2 = new baseX;
baseX* p3 = new baseX;
base& p5(*p2);
baseX& p6 = dynamic_cast<baseX&>(p5);
p6.show();
cin.get();
}