在面向对象中可能出现下面的情况:基类指针指向子类对象,基类引用成为子类对象的别名。
base* p=new Derived();
base& r=*p;
静态类型<->动态类型
静态类型--变量(对象)自身的类型
动态类型--指针(引用)所指向对象的实际类型
void test(base* b) //b指向的类型不确定
{
//危险的转换方式,b指向子类没有问题,将b转换为子类指针。b(父类指针)指向父类的话是不能转换的,成为bug
Derived* d=static_case<Derived*>(b);
}
基类指针是否可以强制类型转换为子类指针取决于动态类型。
c++中如何得到动态类型?
解决方案:利用多态
1,在基类中定义虚函数返回具体的类型信息。
2,所有的派生类都必须实现类型相关的虚函数。
3,每个类中的类型虚函数都需要不同的实现。
#include <iostream>
#include <string>
using namespace std;
class Base
{
public:
virtual string type()
{
return "Base";
}
};
class Derived : public Base{
public:
string type()
{
return "Derived";
}
void printf()
{
cout << "I'm a Derived." << endl;
}
};
class Child : public Base{
public:
string type()
{
return "Child";
}
};
void test(Base* b){
/* 危险的转换方式 */
// Derived* d = static_cast<Derived*>(b);
if( b->type() == "Derived" ) // 如果指向子类
{
Derived* d = static_cast<Derived*>(b);
d->printf();
}
// cout << dynamic_cast<Derived*>(b) << endl; // test(&b);转换不成功打印0,有虚函数用dynamic_cast
}
int main(int argc, char *argv[]){
Base b;
Derived d;
Child c;
test(&b);
test(&d);
test(&c); // 如果用dynamic_cast ,打印0
return 0;
}
dynamic_cast将指向子类对象的父类指针转换为指向子类对象的子类指针。
多态解决方案的缺陷:
必须从基类开始提供类型虚函数,所有的派生类都必须重写类型虚函数,每个派生类的类型名必须唯一。从长期维护不太好。
解决方案2:
c++提供了typeid关键字用于获取类型信息,typeid关键字返回对应参数的类型信息,typeid返回一个type_info类对象,当typeid 的参数为NULL时将抛出异常。使用:
int i=0;
const type_info& tiv=typeid(i);//type_info保存i的类型信息
const type_info& tii=typeid(int);
cout<<(tiv==tii)<<endl;
注意事项:
当参数为类型时:返回静态类型信息。
当参数为变量时:不存在虚函数表-返回静态类型信息。
存在虚函数表:返回动态类型信息。
#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;
class Base
{
public:
virtual ~Base()
{
}
};
class Derived : public Base
{
public:
void printf()
{
cout << "I'm a Derived." << endl;
}
};
void test(Base* b)
{
const type_info& tb = typeid(*b);
cout << tb.name() << endl;
}
int main(int argc, char *argv[])
{
int i = 0;
const type_info& tiv = typeid(i);
const type_info& tii = typeid(int);
cout << (tiv == tii) << endl;
Base b;
Derived d;
test(&b);
test(&d);
return 0;
}
如果没有虚函数(此例为析构函数),b指针指向的对象没有虚函数表,返回静态类型信息,也就是说从b指针自身类型来判断b期望的类型是什么,但是却是不同对象调用的。打印结果一样4Base。有虚函数,返回动态类型信息,打印结果不同4Base,7Derived(不同编译器结果不同,vs没有数字)。
c++中有静态类型和动态类型的概念,静态类型是变量自身的类型,动态类型是指针所指向的实际类型,实际类型在编译阶段无法确定所以叫动态类型,利用多态能够实现对象的动态类型识别,但是维护成本高,typeid是专用于类型识别的关键字,typeid能够返回对象的动态类型信息。