设为首页 加入收藏

TOP

C++中的类型识别(二)
2019-05-24 22:07:50 】 浏览:126
Tags:类型 识别
p; 际不符合的错误,并且造成 if() 语句中的调用不会成功;

   

6,多态解决方案的缺陷:

    1,必须从基类开始提供类型虚函数;

    2,所有的派生类都必须重写类型虚函数;

       1,长期维护并不好;

    3,每个派生类的类型名必须唯一;

   

7,C++ 提供了 typeid 关键字用于获取类型信息:

    1,typeid 关键字返回对应参数的类型信息;

       1,类的和基础类型的类型信息;

    2,typeid 返回一个 type_info 类对象;

    3,当 typeid 的参数为 NULL 时将抛出异常;

       1,参数可以是类型名、变量名;

   

8,typeid 关键字的使用:

    1,代码示例:

1 int i = 0;
2        
3 const type_info& tiv = typeid(i);  // 将 i 的类型信息放到 type_info 中去;
4 const type_info& tii = typeid(int);
5        
6 cout << (tiv == tii) << endl;

      

9,typeid 的注意事项:

    1,当参数为类型时,返回静态类型信息;

    2,当参数为变量时:

       1,参数变量内部不存在虚函数表时,返回静态类型信息;

       2,参数变量内部存在虚函数表时,返回动态类型信息;

      

10,tpeid 类型识别编程实验:

 1 #include <iostream>
 2 #include <string>
 3 #include <typeinfo>  // typeid 返回的对象类型 tyep_info 所对应的头文件;
 4 
 5 using namespace std;
 6 
 7 class Base
 8 {
 9 public:
10     virtual ~Base()
11     {
12     }
13 };
14 
15 class Derived : public Base
16 {
17 public:
18     void printf()
19     {
20         cout << "I'm a Derived." << endl;
21     }
22 };
23 
24 void test(Base* b)
25 {
26     const type_info& tb = typeid(*b);
27     
28     cout << tb.name() << endl;
29 }
30 
31 int main(int argc, char *argv[])
32 {
33     int i = 0;
34     
35     const type_info& tiv = typeid(i);
36     const type_info& tii = typeid(int);
37     
38     cout << (tiv == tii) << endl;  // 1;
39     
40     Base b;
41     Derived d;
42  
43     /* 通过不同的对象调用得到类型信息相同,因为 b 对象没有虚函数表,此时返回静态类型信息 */   
44     test(&b);  // 4Base;
45     test(&d);  // 4Base;
46     
47     /* 对象 b 里加上虚函数表后,返回动态类型信息 */
48     test(&b);    // 4Base;(在 Linux 的 g++ 编译器下面显示的)Base;                     
49            //(在 windows 的 BCC 编译器下面显示的)
50     test(&d);   // 7Derived;(在 Linux 的 g++ 编译器下面显示的)                            
51           // Derived;(在 windows 的 BCC 编译器下面显示的)
52     
53     return 0;
54 }

    1,typeid 在不同的编译器内部实现是不同的;

   

11,小结:

    1,C++ 中有静态类型和动态类型的概念;

    2,利用多态能够实现对象的动态类型识别;

       1,维护成本高,一旦不小心出错,整个项目就会有 bug;

    3,typeid 是专用于类型识别的关键字;

    4,typeid 能够返回对象的动态类型信息;

       1,使用 typeid 的时候,一定不要进行某些类型上面的假设,因为不同的编译器处理类型的名字它的方式是不一样的;

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C++中函数异常规格的说明 下一篇P1108 低价购买 (DP)

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目