首页 | 主题 | 图库 | 问答 | 文摘 | 原创 | 百科

历史 | 地理 | 人物 | 艺术 | 体育 | 科学 | 音乐 | 电影 | 信息技术 | 世界遗产

 开放、中立,源自维基百科

Personal tools

Run-time type information

From Wikipedia, the free encyclopedia

Jump to: navigation, search

In programming, RTTI (Runtime Type Information, or Runtime Type Identification) means keeping information about an object's data type in memory at runtime. Run-time type information can apply to simple data types, such as integers and characters, or to generic objects.

In the case of objects, some implementations are limited to keeping the inheritance tree while others include information about objects' methods and attributes.

Although available in several computer languages, RTTI, as a term, is typically used in relation to C++. In order for the dynamic_cast<> operation, the typeid operator or exceptions to work in C++, RTTI must be enabled.

Example in C++

<source lang="cpp"> /* A base class pointer can point to objects of any class which is derived

* from it. RTTI is useful to identify which type (derived class) of object is 
* pointed by a base class pointer.
*/
  1. include <iostream>

class abc // base class { public:

 virtual void hello() 
 {
   std::cout << "in abc";
 }

};

class xyz : public abc {

 public:
 void hello() 
 {
   std::cout << "in xyz";
 }

};

int main() {

 abc *abc_pointer = new xyz();
 xyz *xyz_pointer;
 // to find whether abc is pointing to xyz type of object
 xyz_pointer = dynamic_cast<xyz*>(abc_pointer);
 if (xyz_pointer != NULL)
   std::cout << "abc pointer is pointing to a xyz class object";   // identified
 else
   std::cout << "abc pointer is NOT pointing to a xyz class object";
 delete abc_pointer;
 return 0;

} </source>


An instance where RTTI is used is illustrated below:

<source lang="cpp"> class base {

 virtual ~base(){}

};

class derived : public base {

 public:
   virtual ~derived(){}
   int compare (derived &ref);

};

int my_comparison_method_for_generic_sort (base &ref1, base &ref2) {

 derived & d = dynamic_cast<derived &>(ref1); // rtti used here
 // RTTI enables the process to throw a bad_cast exception
 // if the cast is not successful
 return d.compare (dynamic_cast<derived &>(ref2));

} </source>

See also

fr:Run-time type information it:RTTI ja:実行時型情報 pl:RTTI pt:RTTI ro:Runtime Type Information ru:Динамическая идентификация типа данных

Languages
AD Links