Micsorft文档阅读笔记-Run-Time Type Information解析及使用

编程入门 行业动态 更新时间:2024-10-27 07:17:05

目录

官方解析

博主栗子


官方解析

Run-Time Type Information解析

Run-time type information (RTTI)运行时类型信息是一个运行机制,这个机制是在程序执行期间要明确一个对象的类型。RTTI在C++中被使用的原因是许多类或者框架实现了很多功能,这就会造成类库间的不兼容。因此,RTTI解决了在语言层面上类库兼容问题。

RTTI几乎都是针对限制于指针问题。然而,讨论的概念也适用于引用。

RTTI在C++中主要的三种情况:
1.dynamic_cast操作符:使用多态类型的转换;
2.typeid操作符:用于识别这个类的具体类型;
3.type_info类:用于保护typeid这个操作符返回后的类型信息;

 

博主栗子

源码一:

#include <iostream>
using namespace std;

class Base {
public:
	void print() {
		cout << "Base print() called!\n";
	}
};

class Child :public Base {
public:
	void print() {
		cout << "Child print() called!\n";
	}
};

void main() {

	Child *child = new Child;
	child->print();

	Base *base = dynamic_cast<Child*>(child);	
	
	//or use it in this way
	//Base *base_2 = child;

	base->print();

	getchar();
}

运行截图如下:

源码二:

#include <iostream>
#include <typeinfo>
using namespace std;

class Base {
public:
	void print() {
		cout << "Base print() called!\n";
	}
};

class Child :public Base {
public:
	void print() {
		cout << "Child print() called!\n";
	}
};

void main() {
	cout << typeid(1).name() << endl;
	cout << typeid(1.1).name() << endl;

	cout << typeid(new Base).name() << endl;
	cout << typeid(*new Base).name() << endl;

	Child *child = new Child;
	Base *base = child;
	cout << typeid(base).name() << endl;
	cout << typeid(*base).name() << endl;

	getchar();
}

运行截图如下:

补充:typeid是在编译时期识别的,关于type_info将在以后的博文中给出

更多推荐

Micsorft文档阅读笔记-Run-Time Type Information解析及使用

本文发布于:2023-06-14 03:42:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1434046.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档   笔记   Micsorft   Run   Information

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!