66-C++中的类型识别
来源:互联网 发布:core keygen for mac 编辑:程序博客网 时间:2024/06/06 10:50
1、类型识别
p指针指向父类对象,根据赋值性原则,父类指向一个子类对象也是合法的。现在p指针指向一个子类对象,可以说指针p的静态类型为Base*(p的本意是指向一个父类对象的,)静态类型是指针指向期望的类型,然而由于赋值兼容性原则,p指向子类的类型,这是指针p所指向的对象为动态类型,动态类型与期望类型有可能是不一样的,r的本意是作为父类对象的别名,但是由于赋值兼容性原则它可以作为一个子类的别名来使用,没有办法判断它是作为父类对象的别名还是子类对象的别名来使用。
2、静态类型和动态类型
3、问题
4、动态类型识别
#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;//这种方法 转换不成功 输出0;}int main(int argc, char *argv[]){ Base b; Derived d; Child c; test(&b); test(&d); test(&c); return 0;}0I'm a Derived.0x7ffed91f54400
5、缺陷
6、类型识别关键字
7、关键字使用
8、注意事项
#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); cout << (tiv == tii) << endl; Base b; Derived d; test(&b); test(&d); return 0;}14Base7Derived//注意 typeid在不同的编译器下,返回的类型名是不一样的
9、小结
阅读全文
0 0
- 66-C++中的类型识别
- 问题:Objective-C 中 C 类型函数不识别 foundation 中的类
- 谈谈Java中的类型识别RTTI
- MFC中的运行时类型识别(RTTI)
- C++_Primer_chapter18 2. 运行时类型识别
- C中的_Bool类型
- C语言中的类型
- C中的字符类型
- C中的布尔类型
- C++中的类型转换与类型识别 1
- C++中的类型转换与类型识别 2
- OC学习笔记(11)Object-C静态类型识别与动态类型识别
- C#.NET 中的类型转换
- C#.NET 中的类型转换
- C#.NET 中的类型转换
- C#.NET 中的类型转换
- C#.NET 中的类型转换
- C#.NET 中的类型转换
- 文件下载
- 收集的RxJava 2.x入门教程系列专栏,文章链接
- 洛谷P3031 中石油2557 Above the Median (数组模拟or树状数组求逆序数)
- 移动端与PC端的测试差异性
- leetcode-448. Find All Numbers Disappeared in an Array
- 66-C++中的类型识别
- 简易Http客户端
- 任务三
- Java(7-3)
- React入门狂想曲(一)
- maven管理spring+springMvc+mybatis搭建
- vuejs在解析时出现闪烁的原因及防止闪烁的方法
- Shell之遍历数组-yellowcong
- iOS精确计算label 的高度