用于子类指针或引用转换为父类指针或引用。
#include <iostream>
using namespace std;
class Base
{
public:
Base() {};
virtual void Show() { cout << "This is Base class"; }
};
class Derived :public Base
{
public:
Derived() {};
void Show() { cout << "This is Derived class"; }
};
int main()
{
Derived* der = new Derived;
auto Derived = static_cast<Base*> (der);
//向上转换不时是安全的
Derived->Show();
system("pause");
}
输出结果为
This is Derived class
存在虚函数重载,则父类的函数被隐藏不能使用。
由于使用dynamic_cast和static_cast方法会存在开销,则一般使用下列方法停止向上转换。
class Base
{
public:
Base(){};
virtual void Show(){cout<<"This is Base class";}
};
class Derived:public Base
{
public:
Derived(){};
void Show(){cout<<"This is Derived class";}
};
int main()
{
Base *base ;
Derived *der = new Derived;
//向上转换总是安全
base = der;
base->Show();
system("pause");
}
此处和static_cast是一样的,不再过多叙述。
#include <iostream>
using namespace std;
class Base
{
public:
Base() {};
virtual void Show() { cout << "This is Base calss"; }
};
class Derived :public Base
{
public:
Derived() {};
void Show() { cout << "This is Derived class"; }
};
int main()
{
Derived* der = new Derived;
auto Derived = dynamic_cast<Base*> (der);
//向上转换不时是安全的
Derived->Show();
system("pause");
}
3.2 类的下行转换(安全)
因为有类型检查所以是安全的,但类型检查需要运行时类型信息,这个信息位于虚函数表中,所以必需要有虚函数,否则会转换失败。
在dynamic_cast转换中分为两种情况。
1、当基类指针指向派生对象时可以安全转换。
2、基类指针指向基类时会做检查,转换失败,返回结果0。
#include <iostream>
using namespace std;
class Base
{
public:
Base() {};
virtual void Show() { cout << "This is Base class" << endl; }
};
class Derived :public Base
{
public:
Derived() {};
void Show() { cout << "This is Derived class" << endl; }
};
int main()
{
//第一种情况
Base* base = new Derived;
Derived* der = dynamic_cast<Derived*>(base);
//基类指针指向派生类对象时可以安全转换
der->Show();
//第二种情况
Base *base1 = new Base;