dynamic_cast

dynamic_cast

Dans le langage de programmation C++, l'opérateur dynamic_cast est un membre du système de run-time type information (RTTI) qui effectue une conversion de type. Cependant, contrairement au cast hérité du langage C, une vérification du type est effectuée à l'exécution, et lèvera soit une exception dans le cas des références, soit un pointeur nul dans le cas des pointeurs, si les types ne sont pas compatibles. Donc, dynamic_cast se comporte plus comme un convertisseur de type dans un langage tel que Java, plutôt qu'une conversion au sens du langage C, qui ne vérifie rien à l'exécution.

Le dynamic_cast est relativement coûteux à l'exécution. Il devrait être utilisé aussi peu que possible.

Sommaire

Exemple de code

Supposons qu'une méthode prenne un objet de type A en argument, laquelle effectuerait quelques traitements supplémentaires si l'objet est en fait une instance de type B, une classe dérivée de A. Ceci peut être réalisé à l'aide de dynamic_cast comme suit.

#include <typeinfo> // Pour std::bad_cast
#include <iostream> // Pour std::cerr, etc.
 
class A
{
public:
        // Puisque RTTI est incluse dans la table des méthodes virtuelles, il devrait y avoir au moins une fonction virtuelle.
        virtual void foo();
 
        // autres membres...
};
 
class B : public A
{
public:
        void methodSpecificToB();
 
        // autres membres...
};
 
void my_function(A& my_a)
{
        try
        {
                B& my_b = dynamic_cast<B&>(my_a);
                my_b.methodSpecificToB();
        }
        catch (const std::bad_cast& e)
        {
                std::cerr << e.what() << std::endl;
                std::cerr << "Cet object n'est pas de type B" << std::endl;
        }
}

Une version équivalente de my_function peut être écrite avec utilisation de pointeurs au lieu de références :

void my_function(A* my_a)
{
        B* my_b = dynamic_cast<B*>(my_a);
 
        if (my_b != NULL)
                my_b->methodSpecificToB();
        else
            std::cerr << "Cet object n'est pas de type B" << std::endl;
 
 
}

Voir aussi

Articles connexes

Sur les autres projets Wikimedia :

  • static cast
  • reinterpret cast
  • const cast

Liens externes


Wikimedia Foundation. 2010.

Contenu soumis à la licence CC-BY-SA. Source : Article dynamic_cast de Wikipédia en français (auteurs)

Игры ⚽ Поможем написать реферат

Regardez d'autres dictionnaires:

  • dynamic_cast — В языке программирования C++, оператор dynamic cast является частью механизма динамической идентификации типа данных, который позволяет выполнять приведение типа данных. В отличие от обычного приведения типа в стиле Си, проверка корректности… …   Википедия

  • dynamic_cast — In the C++ programming language, the dynamic cast operator is a part of the run time type information (RTTI) system that performs a typecast. Unlike an ordinary C style typecast, a type safety check is performed at runtime, and if the types are… …   Wikipedia

  • Dynamic cast — В языке программирования C++, оператор dynamic cast является частью механизма динамической идентификации типа данных, который позволяет выполнять приведение типа данных. В отличие от обычного приведения типа в стиле Си, проверка корректности… …   Википедия

  • Multiple dispatch — Theories and practice of polymorphism Double dispatch Multiple dispatch Operator overloading Polymorphism in computer science Polymorphism in OOP Subtyping …   Wikipedia

  • Dynamic cast — In the C++ programming language, the dynamic cast operator is a part of the run time type information (RTTI) system that performs a typecast. However, unlike an ordinary C style typecast, a type safety check is incurred at runtime, and it will… …   Wikipedia

  • Динамическая идентификация типа данных — Не следует путать с динамической типизацией. Динамическая идентификация типа данных (англ. Run time type information, Run time type identification, RTTI)  механизм в некоторых языках программирования, который позволяет определить тип… …   Википедия

  • Run-time type information — In programming, RTTI (Run Time Type Information, or Run Time Type Identification) refers to a C++ system that keeps information about an object s data type in memory at runtime. Run time type information can apply to simple data types, such as… …   Wikipedia

  • Динамическая идентификация типа — данных (англ. Run time Type Information, Run time Type Identification, RTTI)  механизм, реализованный в языках программирования, который позволяет определить тип данных переменной или объекта во время выполнения программы. Содержание 1 Реализация …   Википедия

  • Множественная диспетчеризация — Мультиметод (англ. multimethod) или множественная диспетчеризация (англ. multiple dispatch) это механизм, позволяющий выбрать одну из нескольких функций в зависимости от динамических типов аргументов. Таким образом, в отличие от обычных… …   Википедия

  • Operators in C and C++ — This is a list of operators in the C and C++ programming languages. All the operators listed exist in C++; the fourth column Included in C , dictates whether an operator is also present in C. Note that C does not support operator overloading.… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”