zoukankan      html  css  js  c++  java
  • C++语法小记---类型检测

    类型检测
    • C++使用typeid关键字进行类型检查

    • 不同的编译器使用typeid返回的类型名称不严格一致,需要特别注意

    • 也可以使用虚函数,返回各自的类型名

    • 如果typeid的操作数不是类类型(类指针也算)或者是没有虚函数的类,则typeid指出该操作数的静态类型。如果操作数是定义了至少一个虚函数的类类型,则在运行时计算类型

     1 #include <iostream>
     2 #include <string>
     3 #include <typeinfo>
     4 
     5 using namespace std;
     6 
     7 class Base 
     8 {
     9 public:
    10     virtual void func() {}
    11 };
    12 
    13 class Derived : public Base 
    14 {
    15 };
    16 
    17 int main() 
    18 {
    19     Derived* pd = new Derived;
    20     Base* pb = pd;
    21 
    22     cout << typeid( pb ).name() << endl;   // prints "class Base *"  类指针 --- 静态类型
    23     cout << typeid( *pb ).name() << endl;  // prints "class Derived"
    24     cout << typeid( pd ).name() << endl;   // prints "class Derived *"
    25     cout << typeid( *pd ).name() << endl;  // prints "class Derived"
    26 
    27     delete pd;
    28     return 029 }
  • 相关阅读:
    python中xrange和range的异同
    Python:使用threading模块实现多线程编程
    python Queue模块
    Python中pass语句的作用
    Python的作用域
    eclipse颜色配置
    protobuf
    python调试总结
    chardet安装
    Windows下搭建PHP开发环境
  • 原文地址:https://www.cnblogs.com/chusiyong/p/11315632.html
Copyright © 2011-2022 走看看