从零开始学C++之RTTI、dynamic_cast、typeid、类与类之间的关系uml

本文详细介绍了C++中的RTTI(运行时类型信息)机制,包括dynamic_cast和typeid操作符的应用,并探讨了UML中类之间的五种关系:继承、关联、聚合、组合与依赖。

一、RTTI
Run-time type information (RTTI) is a mechanism that allows the type of an object to be determined during program execution.

There are three main C++ language elements to run-time type information:
The dynamic_cast operator.
Used for conversion of polymorphic types.
The typeid operator.
Used for identifying the exact type of an object.
The type_info class.
Used to hold the type information returned by the typeid operator.

class type_info {
public:
    virtual ~type_info();
    bool operator==(const type_info& rhs) const;
    bool operator!=(const type_info& rhs) const;
    int before(const type_info& rhs) const;
    const char* name() const;
    const char* raw_name() const;
private:
    void *_m_data;
    char _m_d_name[1];
    type_info(const type_info& rhs);
    type_info& operator=(const type_info& rhs);
    static const char _Name_base(const type_info *,__type_info_node* __ptype_info_node);
};

The result of typeid is a const type_info&. The value is a reference to a type_info object that represents either the type-id or the type of the expression, depending on which form of typeid is used.

为了支持RTTI,为每一个多态类创建一个type_info 对象(静态数据区),并把其地址保存到vtable中的固定位置(一般为第一个位置)(取决于具体编译器实现,标准并没有规定)。

#include <iostream>
using namespace std;

class Shape
{
public:
    virtual void Draw() = 0;
    virtual ~Shape() {}
};

class Circle : public Shape
{
public:
    void Draw()
    {
        cout << "Circle Draw ..." << endl;
    }
};

class Square : public Shape
{
public:
    void Draw()
    {
        cout << "Square Draw ..." << endl;
    }
};

int main(void)
{
    Shape *p;
    Circle c;

    p = &c;
    p->Draw();

    //使用dynamic_cast 的条件
    //1、开启运行时类型信息;2、应用在具有多态关系的继承体系上;
    if (dynamic_cast<Circle *>(p))
    {
        cout << "p is point to a Circle object" << endl;
        Circle *cp = dynamic_cast<Circle *>(p);     // 安全向下转型
        cp->Draw(); //效率没有 p->Draw(); 高
    }
    else if (dynamic_cast<Square *>(p))
    {
        cout << "p is point to a Square object" << endl;
    }
    else
    {
        cout << "p is point to a Other object" << endl;
    }

    cout << typeid(*p).name() << endl;
    cout << typeid(Circle).name() << endl;
    if (typeid(Circle).name() == typeid(*p).name())
    {
        cout << "p is point to a Circle object" << endl;
        ((Circle *)p)->Draw();
    }
    else if (typeid(Square).name() == typeid(*p).name())
    {
        cout << "p is point to a Circle object" << endl;
        ((Square *)p)->Draw();
    }
    else
    {
        cout << "p is point to a Other object" << endl;
    }

    return 0;
}

这里写图片描述
如上所述,dynamic_cast 和 typeid 操作符 都可以实现运行时类型识别。其中使用dynamic_cast 时需要开启运行时类型信息,在项目-》属性-》C/C++-》语言-》启用运行时类型信息。在使用typeid时需要注意的是返回的是type_info 对象的引用,且type_info 类的拷贝构造函数和赋值运算符都声明为私有,故不能这样写: type_info tf = typeid(Circle);

二、类与类之间的关系
Unified Modeling Language (UML)又称统一建模语言或标准建模语言,是始于1997年一个OMG标准,它是一个支持模型化和软件系统开发的图形化语言。
1、继承(泛化)Generalization
这里写图片描述
Manager 继承自Employee.

2、关联 Association,单向关联 DirectedAssociation
这里写图片描述
Order 作为Customer 的成员,如vector orders ;

3、聚合 Aggregation
这里写图片描述

class B
class A
{ 
    public:
    B* b_;
};

当A释放时,不负责B的释放,也许B是被共享的。

4、组合 Composition
这里写图片描述
当Company 释放时要负责Department 的释放,Department 不是共享的。

5、依赖 Dependency
这里写图片描述
类A依赖于B:
从语义上来上是A use B,偶然的,临时的
B作为A的成员函数参数
B作为A的成员函数的局部变量
A的成员函数调用B的静态方法

比较5种关系:
继承体现的是类与类之间的纵向关系,其他4种体现的是类与类之间的横向关系。
关联强弱
依赖<关联<聚合<组合
继承(A is B)
关联、聚合、组合(A has B)
依赖(A use B)

参考:
C++ primer 第四版
Effective C++ 3rd
C++编程规范

转载自http://blog.youkuaiyun.com/jnu_simba/article/details/9320275

<think>我们被要求回答关于C++四种型转换操作符的区别和用法:static_cast, dynamic_cast, const_cast, reinterpret_cast。 根据提供的引用,我们可以总结如下: 1. static_cast: - 用于基本型转换(如int转double)和具有明确继承关系指针或引用的转换(向上转换是安全的,向下转换不安全)。 - 不进行运行时型检查,因此向下转换(基指针转派生指针)可能不安全。 - 也可以用于非多态型的转换。 2. dynamic_cast: - 主要用于多态型(即含有虚函数的)的安全转换,特别是在继承体系中向下转换(基指针/引用转派生指针/引用)或交叉转换。 - 运行时检查转换的有效性。如果转换失败,对于指针返回nullptr,对于引用抛出std::bad_cast异常。 - 要求基至少有一个虚函数(以提供运行时型信息)。 3. const_cast: - 用于移除或添加变量的const(或volatile)属性。 - 常用于函数重载或非const API交互时,但需注意修改原为const的对象是未定义行为。 4. reinterpret_cast: - 提供低级别的重新解释,如将指针转换为整数,或将一种型的指针转换为另一种不相关型的指针。 - 非常危险,因为不进行任何型检查,应尽量避免使用,仅在底层编程(如系统调用、驱动开发)中必要时使用。 我们将按照这些要点组织回答,并给出简单示例。 同时,根据要求,我们需要生成相关问题。 注意:回答中引用的段落末尾要自然地添加引用标识,例如:[^1] 我们引用的内容来自提供的引用[1]到[5],但注意我们只能使用这些引用,不能引入外部知识。 由于用户要求使用中文回答,且数表达式用$...$,独立公式用$$...$$,但本问题中可能涉及较少数公式,我们按需使用。 步骤: 1. 分别介绍四种转换,说明区别和使用场景。 2. 给出简单代码示例(注意:由于是文本,我们只写关键代码片段)。 3. 生成相关问题。 注意:我们引用的内容在回答中需要标注引用标识,例如:dynamic_cast在运行时进行型检查[^4]。</think>### C++型转换操作符详解 C++提供了四种显式型转换操作符,用于在不同场景下进行安全或强制的型转换: #### 1. `static_cast`(静态转换) - **用途**:基本型转换、明确的继承关系转换(如向上转型) - **特点**: - 编译时检查,无运行时开销 - 向下转型(基→派生)不安全,可能导致未定义行为 - 不能移除`const`限定符 - **示例**: ```cpp double d = 3.14; int i = static_cast<int>(d); // 基本型转换 Base* base = new Derived(); Derived* derived = static_cast<Derived*>(base); // 向下转型(风险!) ``` #### 2. `dynamic_cast`(动态转换) - **用途**:安全的多态型转换(需虚函数支持) - **特点**: - 运行时型检查(RTTI),失败返回`nullptr`(指针)或抛出异常(引用) - 主要用于继承体系中的向下转型和交叉转换 - 比`static_cast`安全但性能开销较大[^4] - **示例**: ```cpp class Base { virtual void foo() {} }; // 必须含虚函数 class Derived : public Base {}; Base* base = new Derived(); Derived* derived = dynamic_cast<Derived*>(base); // 安全向下转型 if(derived) { /* 转换成功 */ } // 运行时检查 ``` #### 3. `const_cast`(常量转换) - **用途**:移除或添加`const`/`volatile`限定符 - **特点**: - 不修改底层数据,仅改变编译器解释 - 修改原为`const`的对象是未定义行为[^2] - 常用于兼容非`const` API - **示例**: ```cpp const int x = 10; int* y = const_cast<int*>(&x); // 移除const限定 *y = 20; // 危险!原对象x仍是const ``` #### 4. `reinterpret_cast`(重新解释转换) - **用途**:底层二进制数据重新解释 - **特点**: - 最危险的转换,不进行任何型检查 - 常用于系统编程(如指针↔整数转换) - 高度平台依赖,应作为最后手段[^2][^5] - **示例**: ```cpp int x = 10; long ptr_val = reinterpret_cast<long>(&x); // 指针→整数 int* ptr = reinterpret_cast<int*>(ptr_val); // 整数→指针 ``` ### 关键区别总结 | 操作符 | 检查时机 | 安全性 | 典型场景 | |----------------|-----------|-------------|----------------------------| | `static_cast` | 编译时 | 中等(无RTTI)| 基础型转换、明确继承关系转换 | | `dynamic_cast` | 运行时 | 高 | 多态型安全向下转型 | | `const_cast` | 编译时 | 低(语义风险)| 临时移除`const`限定 | | `reinterpret_cast` | 无检查 | 极低 | 底层二进制数据重新解释 | > 最佳实践:优先使用`dynamic_cast`保证多态安全;避免`reinterpret_cast`;谨慎使用`const_cast`修改原`const`对象[^2][^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值