马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
C++中的范例转换(Type Conversion)是指将一个数据范例的值转换为另一个数据范例的过程,重要包罗:
一、算术范例转换(Arithmetic Conversions)
算术范例转换通常发生在算术运算或比力中,称为**“标准转换”(standard conversion),遵照一定的提升规则(promotion rules)**。
转换规则(简化版):
- bool → int
- 整型提升:char、short → int
- 两个操纵数差别范例时:
- 若一个为浮点型,另一个为整型 → 整型转换为浮点型
- 若一个为double,另一个为float → float 转为 double
- 若一个为unsigned且它的值不能用int体现 → int转为unsigned
- 否则,unsigned提升优先级高于signed
示例:
- #include <iostream>
- int main() {
- char c = 100;
- int i = 200;
- float f = 1.5f;
- double d = 3.14;
- auto result1 = c + i; // char → int,结果是 int
- auto result2 = i + f; // int → float,结果是 float
- auto result3 = f + d; // float → double,结果是 double
- std::cout << "result1: " << result1 << "\n"; // 300
- std::cout << "result2: " << result2 << "\n"; // 201.5
- std::cout << "result3: " << result3 << "\n"; // 4.64
- }
复制代码 二、其他隐式范例转换(Implicit Conversion)
这是 编译器主动完成 的转换,也叫范例提升(promotion)或范例协同(coercion)。
常见的隐式转换:
范例转换方向示例数值型更大/更精度的数值int → double指针范例派生类 → 基类Derived* → Base*空指针nullptr → 任何指针范例nullptr → int*数组/函数 → 指针int arr[] → int*示例:
- void printDouble(double d) {
- std::cout << "Double: " << d << "\n";
- }
- class Base {};
- class Derived : public Base {};
- int main() {
- int i = 42;
- printDouble(i); // int → double(隐式)
- Derived d;
- Base* bptr = &d; // Derived* → Base*(隐式)
- }
复制代码 三、显示范例转换(Explicit Conversion / Cast)
你可以显式地指示编译器举行范例转换,有四种标准C++风格的转换方式(保举),以及一个C风格的转换(不保举)。
四种C++显式转换:
- static_cast<T>(expr)
➤ 用于根本范例之间转换、指针/引用向上转换等安全转换。
- dynamic_cast<T>(expr)
➤ 用于带有虚函数的多态类之间的安全运行时范例查抄和向下转换。
- const_cast<T>(expr)
➤ 添加或去除const、volatile限定符,常用于函数参数处置惩罚。
- reinterpret_cast<T>(expr)
➤ 不安全但允许的位级别转换,如指针与整数之间转换。
- (T)expr —— C风格欺压转换
➤ 组合了上述全部功能,不安全不透明,不保举使用。
示例:
- #include <iostream>
- class Base { public: virtual ~Base() {} };
- class Derived : public Base { public: void say() { std::cout << "Derived\n"; } };
- int main() {
- int i = 100;
- double d = static_cast<double>(i); // int → double
- Base* b = new Derived();
- Derived* dptr = dynamic_cast<Derived*>(b); // 安全向下转型
- if (dptr) dptr->say();
- const int ci = 42;
- int* p = const_cast<int*>(&ci); // 去除 const 限定
- void* vptr = reinterpret_cast<void*>(p); // int* → void*
- int* iptr = reinterpret_cast<int*>(vptr); // void* → int*
- delete b;
- }
复制代码 四、总结对比表:
转换范例触发方式安全性用途/阐明算术转换主动安全数值运算中的标准提升隐式转换主动通常安全函数调用/指针/根本范例提升static_cast显式安全编译期可查抄的转换,如 int→float,向上转型dynamic_cast显式安全多态范例的运行时向下转型const_cast显式有风险去除 const/volatilereinterpret_cast显式不安全位级别转换,极度环境用C风格欺压转换显式不保举混合多个C++转换,缺乏范例安全五、综合例子
下面是一个C++ 示例工程,通过一个模仿图形系统的类结构,演示了**各种范例转换(隐式、算术、显示转换)**的组合使用。代码里有表明,方便理解每一种转换在什么时候触发、为什么安全大概不安全。
界说 shape.h图形类头文件内容如下:
- #pragma once
- #include <iostream>
- #include <string>
- class Shape {
- public:
- virtual ~Shape() {}
- virtual void draw() const;
- };
- class Circle : public Shape {
- public:
- Circle(double r);
- void draw() const override;
- double getRadius() const;
- private:
- double radius;
- };
- class Rectangle : public Shape {
- public:
- Rectangle(int w, int h);
- void draw() const override;
- int area() const;
- private:
- int width, height;
- };
- // 模拟图形渲染系统的底层资源对象
- struct RenderHandle {
- void* data;
- };
- RenderHandle createHandle(int id);
复制代码 shape.cpp 图形类实现如下:
- #include "shape.h"
- void Shape::draw() const {
- std::cout << "Drawing Shape\n";
- }
- Circle::Circle(double r) : radius(r) {}
- void Circle::draw() const {
- std::cout << "Drawing Circle with radius: " << radius << "\n";
- }
- double Circle::getRadius() const {
- return radius;
- }
- Rectangle::Rectangle(int w, int h) : width(w), height(h) {}
- void Rectangle::draw() const {
- std::cout << "Drawing Rectangle of area: " << area() << "\n";
- }
- int Rectangle::area() const {
- return width * height;
- }
- RenderHandle createHandle(int id) {
- RenderHandle h;
- h.data = reinterpret_cast<void*>(id); // 显式 reinterpret_cast
- return h;
- }
复制代码 main.cpp 主函数演示各种范例转换示例内容如下:
- #include "shape.h"
- #include <typeinfo>
- void printDouble(double d) {
- std::cout << "Double value: " << d << "\n";
- }
- int main() {
- // 算术类型转换(int → double)
- int i = 42;
- double d = i; // 隐式转换
- printDouble(d); // 参数是 double
- float f = static_cast<float>(i); // 显式 static_cast
- std::cout << "Float from int: " << f << "\n";
- // 基类 → 派生类的动态转换(dynamic_cast)
- Shape* s = new Circle(3.5);
- s->draw();
- if (Circle* c = dynamic_cast<Circle*>(s)) {
- std::cout << "Radius from casted circle: " << c->getRadius() << "\n";
- }
- // const_cast 演示
- const int ci = 100;
- int* modifiable = const_cast<int*>(&ci);
- *modifiable = 999; // 未定义行为,仅演示用
- std::cout << "Modified const int (unsafe!): " << *modifiable << "\n";
- // reinterpret_cast 演示
- int resourceID = 1234;
- RenderHandle h = createHandle(resourceID);
- int recoveredID = reinterpret_cast<int>(h.data);
- std::cout << "Recovered ID from RenderHandle: " << recoveredID << "\n";
- // 隐式派生 → 基类(安全)
- Rectangle rect(10, 20);
- Shape* s2 = ▭
- s2->draw(); // 虚函数,多态行为
- delete s;
- return 0;
- }
复制代码 示例的演示内容如下:
场景范例转换涉及关键字/方式int → double算术隐式转换主动float ← int算术显式转换static_castBase* ← Derived*隐式向上转换主动Derived* ← Base*安全运行时转换dynamic_castconst int* ← int*添加/去除 constconst_castvoid* ←→ int指针/整数转换reinterpret_castShape 多态活动虚函数机制隐式 |