基类指针指向子类对象
基类引用成为子类对象的别名
静态类型 - 变量(对象)自身的类型
动态类型-指针(引用)所指向对象的实际类型
解决 -利用多态
- 1.基类中定义虚函数返回具体类型信息
- 2.所有派生类都必须实现类型相关的虚函数
- 3.没个类的类型虚函数都需要不同的实现
示例1
#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'am a Derived" << endl;
}
};
class Child : public Base
{
public:
string type()
{
return "Child";
}
};
void Test(Base* b)
{
cout << b->type() << endl;
if(b->type() == "Derived")
{
Derived* d = static_cast<Derived*>(b);
d->printf();
}
}
int main(int argc, char *argv[])
{
Base b;
Derived d;
Child c;
Test(&b);
Test(&d);
Test(&c);
return 0;
}
多态缺陷
- 必须从基类开始提供类型虚函数
- 所有派生类都必须重写类型虚函数
- 每个派生类的类型名必须唯一
C++提供typeid关键字获取类型信息
- typeid关键字返回对应参数的类型信息
- typeid返回一个type_info乐力对象
- 当typeid的参数为NULL时将抛出异常
示例二
#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;
class Base
{
public:
virtual ~Base()
{
}
};
class Derived : public Base
{
public:
void printf()
{
cout << "I'am 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;
}
小结
- C++中有静态类型和动态类型
- 利用多态能够实现对象的动态类型识别
- typeid是专用类型识别的关键字
- typeid能够返回对象的动态信息