C++笔记 第六十六课 C++中的类型识别(新内容的最后一课)---狄泰学院

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_42187898/article/details/84651191

如果在阅读过程中发现有错误,望评论指正,希望大家一起学习,一起进步。
学习C++编译环境:Linux

第六十六课 C++中的类型识别(新内容的最后一课)

1.类型识别

在面向对象中可能出现下面的情况
基类指针指向子类对象
基类引用成为子类对象的别名
在这里插入图片描述
静态类型-变量(对象)自身的类型
动态类型-指针(引用)所指向的对象的实际类型
在这里插入图片描述
基类指针是否可以强制类型转换为子类指针取决于动态类型!

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

3.动态类型识别

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

66-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'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;//有继承关系的类,有虚函数可用dynamic_cast
运行结果
0    //动态类型是base,到dynamic_cast强转,不成功,B指向父类对象,空指针,返回0
I'm a Derived.   //
0x7fff85f5a8a0  //
0             //同上
}
int main(int argc, char *argv[])
{
    Base b;
    Derived d;
    Child c;
    
    test(&b);
    test(&d);//合法
    test(&c);
    
    return 0;
}
运行结果
I'm a Derived.

多态解决方案的缺陷
必须从基类开始提供类型虚函数
所有的派生类都必须重写类型虚函数
每个派生类的类型名必须唯一

4.类型识别关键字

C++提供了typeid关键字用于获取类型信息
typeid关键字返回对于参数的类型信息
typeid返回一个type_info类对象
当typeid的参数为NULL时将抛出异常
typeid关键字的使用
在这里插入图片描述

5.动态类型识别

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

66-2 typeid类型识别

#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);//得到int类型信息
    
    cout << (tiv == tii) << endl;
    
    Base b;
    Derived d;
    
    test(&b);
    test(&d);
    
    return 0;
}
运行结果
1
4Base
7Derived

小结
C++中有静态类型和动态类型的概念
利用多态能够实现对象的动态类型识别
typeid是专用于类型识别的关键字
typeid能够返回对象的动态类型信息

猜你喜欢

转载自blog.csdn.net/weixin_42187898/article/details/84651191