1.类型识别

在面向对象中可能出现下面的情况
—-基类指针指向子类对象
—-基类引用成为子类对象的别名
Base p = new Derived();
(静态类型) (动态类型)
Base& r =
p;

这里无法确定指针是指向父类还是子类的

静态类型—-变量(对象)自身的类型
动态类型—-指针(引用)所指向对象的实际类型
void test(Base b)
{
/
危险的转换方式?
Derived
d = static_cast(b);
}
基类指针是否可以强制类型转换,为子类指针取决于动态类型!

2.c++中如何得到动态类型

解决方案—-利用多态
1.在基类中定义虚函数返回基本的类型信息
2.所有派生类必须实现类型相关的虚函数
3.每个类中的类型虚函数都需要不同的实现

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. class Base
  5. {
  6. public:
  7. virtual string type()
  8. {
  9. return "Base";
  10. }
  11. };
  12. class Derived : public Base
  13. {
  14. public:
  15. string type()
  16. {
  17. return "Derived";
  18. }
  19. void printf()
  20. {
  21. cout << "I'm a Derived." << endl;
  22. }
  23. };
  24. class Child : public Base
  25. {
  26. public:
  27. string type()
  28. {
  29. return "Child";
  30. }
  31. };
  32. void test(Base* b)
  33. {
  34. /* 危险的转换方式 */
  35. // Derived* d = static_cast<Derived*>(b);
  36. if( b->type() == "Derived" )
  37. {
  38. Derived* d = static_cast<Derived*>(b);
  39. d->printf();
  40. }
  41. // cout << dynamic_cast<Derived*>(b) << endl;
  42. }
  43. int main(int argc, char *argv[])
  44. {
  45. Base b;
  46. Derived d;
  47. Child c;
  48. test(&b);
  49. test(&d);
  50. test(&c);
  51. return 0;
  52. }

3.c++中的类型识别关键字

c++中提供了typeid关键字用于获取类型信息
—-typeid关键字返回对应参数的类型信息
—-typeid返回一个type_info类对象
—-当typeid的参数为NULL时将抛出异常

使用:
int i = 0;

const type_info & tiv = typeid(i); //tiv标识i的类型信息
const type_info & tii = typeid(int); //tii标识int的类型信息

cout << (tiv == tii) << endl;

typeid的注意事项:
—-当参数为类型时:返回静态类型信息
—-当参数为变量时:
不存在虚函数表—-返回静态类型信息
存在虚函数表—-返回动态类型信息

  1. #include <iostream>
  2. #include <string>
  3. #include <typeinfo>
  4. using namespace std;
  5. class Base
  6. {
  7. public:
  8. //virtual ~Base() //有虚函数表将返回动态类型信息
  9. ~Base
  10. {
  11. }
  12. };
  13. class Derived : public Base
  14. {
  15. public:
  16. void printf()
  17. {
  18. cout << "I'm a Derived." << endl;
  19. }
  20. };
  21. void test(Base* b)
  22. {
  23. const type_info& tb = typeid(*b);
  24. cout << tb.name() << endl;
  25. }
  26. int main(int argc, char *argv[])
  27. {
  28. int i = 0;
  29. const type_info& tiv = typeid(i);
  30. const type_info& tii = typeid(int);
  31. cout << (tiv == tii) << endl;
  32. Base b;
  33. Derived d;
  34. test(&b);
  35. test(&d);
  36. return 0;
  37. }

小结

1.c++中有静态类型和动态类型的概念
2.利用多态能够实现对象的动态类型识别
3.typeid是专用于类型识别的关键字
4.typeid能够返回对象的动态类型信息