首先dynamic_cast:
#include <iostream>
using namespace std;
class A{
public:
virtual ~A(){} //使用dynamic_cast时,必要!
};
class B:public A{
public:
B(){
m_b=12;
}
void foo(){
cout<<"B: "<<m_b<<endl;
}
private:
int m_b;
};
int main()
{
A *a=new B();
B *b=dynamic_cast<B*>(a);
b->foo();
delete a;
return 0;
}
上面没有virtual ~A(){},编译时会报错:(source type is not polymorphic)。
static_cast:
#include <iostream>
using namespace std;
class A{
public:
A():m_a(32){}
void foo(){
cout<<"A: "<<m_a<<endl;
}
void setA(int a){
m_a=a;
}
private:
int m_a;
};
class B:public A{
public:
B(){
m_b=12;
setA(13);
}
void foo(){
cout<<"B: "<<m_b<<endl;
}
private:
int m_b;
};
int main()
{
A *a=new B();
B *b=static_cast<B*>(a);
A *aa=static_cast<A*>(b);
b->foo();
aa->foo();
delete a;
return 0;
}
打印a、b、aa地址,可知地址一样。