C++复习补充 类型转换和RTTI
类型转换和RTTI
- 类型转换
- 类与类之间的类型转换
- 四种显示类型转换
- 类型转换注意事项
- RTTI
类型转换
在 C++ 中,operator int() 是用户定义的类型转换运算符(User-Defined Conversion Operator),允许自定义对象隐式或显式转换为特定类型。除了 operator int(),你还可以定义其他类型的转换运算符,包括常见的内置类型整形和浮点数,或者指针,或者其他自定义对象
类与类之间的类型转换
//#include"List.h"
//int main()
//{
// bit::list<int> lt = { 1,2,3,4 };
// // 权限缩小?权限缩小和放大,仅限于const的指针和引用
// // 这里不是权限缩小,这里是自定义类型=自定义类型之间的类型转换,重载构造函数或者类型转换
// // 因为const_iterator是两个不同的类,重载构造函数实现
// // 具体实现看下面ListIterator中对应的构造函数的实现
// bit::list<int>::const_iterator cit = lt.begin();
//
// while (cit != lt.end())
// {
// cout << *cit << " ";
// ++cit;
// }
// cout << endl;
// return 0;
//}
类转换其他类有两种方式
重载类型转换
operator otherclass()
{};
想转换的构造函数支持该参数类型
otherclass(myclass )
{}
// iterator
//struct ListIterator<T, T&, T*>
//{
// typedef ListNode<T> Node;
// typedef ListIterator<T, Ref, Ptr> Self;
// Node* _node;
// ListIterator(Node* node)
// :_node(node)
// {}
//
// ListIterator(const ListIterator<T, T&, T*>& it)
// :_node(it._node)
// {}
//};
//
const_iterator
//struct ListIterator<T, const T&, const T*>
//{
// typedef ListNode<T> Node;
// typedef ListIterator<T, Ref, Ptr> Self;
// Node* _node;
// ListIterator(Node* node)
// :_node(node)
// {}
//
// ListIterator(const ListIterator<T, T&, T*>& it)
// :_node(it._node)
// {}
//};
四种显示类型转换
- static_cast
用途:编译时已知类型关系的安全转换。
典型场景:
基础类型之间的显式转换(如 int→double)。
父子类指针/引用的上行转换(子类→父类)。
无继承关系的自定义类型转换(需定义转换构造函数或 operator)。
- dynamic_cast
用途:运行时多态类型的安全下行转换(父类→子类)。
条件:
操作数必须为多态类型(类有虚函数)。
必须启用 RTTI(运行时类型信息)。
- const_cast
用途:修改 const 或 volatile 属性。
典型场景:
调用遗留 API 时去除 const(如 char* 参数需要修改)。
强制修改本应为非 const 的变量(需确保逻辑安全)。
- reinterpret_cast
用途:低级别指针类型转换或指针与整数间的转换。
典型场景:
指针与整数之间的互转(如内存地址操作)。
不相关指针类型之间的强制转换(如 int→char)。
类型转换注意事项
C++不是类型安全的语言,一方面用户写的自定义转换符默认支持隐式类型转换如果说考虑不全面可能会在不想要类型转换的时候隐式类型转换了(最好用explicit修饰),其次四种显示类型转换会绕过编译器检查
RTTI
RTTI是通过多态和typid来保证的,只有在多态基类必须具有虚函数表且对象必须是指向基类的指针和引用才能保证。
dynamic_cast<>支持基类向子类的显示类型转换,只有基类本身是指向子类对象的指针和引用才成立,否则会抛异常