乐闻世界logo
搜索文章和话题

Regular cast vs. Static_cast vs. Dynamic_cast

1个答案

1

In C++, type conversion is used to convert variables of one data type to another. C++ provides several type conversion operations, including C-style casts and more specialized conversion operations such as static_cast and dynamic_cast.

C-style Cast

C-style casts represent the most fundamental type of conversion, with syntax similar to C language conversions. They can be applied to almost any type of conversion, including conversions of basic data types and pointer types. C-style casts lack type safety checks, so they require careful usage to avoid runtime errors.

cpp
int i = 10; double d; d = (double)i; // Convert integer to double-precision floating-point

static_cast

static_cast is a safer type conversion in C++, as it validates the conversion at compile time. It is suitable for conversions of non-polymorphic types, such as conversions of basic data types and converting derived class pointers to base class pointers.

cpp
class Base {}; class Derived : public Base {}; Derived *d = new Derived(); Base *b = static_cast<Base*>(d); // Convert derived class pointer to base class pointer

dynamic_cast

dynamic_cast is specifically designed for handling polymorphic types. It checks type safety at runtime. If the conversion fails, it returns a null pointer (for pointer types) or throws an exception (for reference types). dynamic_cast is primarily used for safely converting base class pointers or references to derived class pointers or references.

cpp
class Base { public: virtual void print() { std::cout << "Base" << std::endl; } }; class Derived : public Base { public: void print() override { std::cout << "Derived" << std::endl; } }; Base *b = new Derived(); Derived *d = dynamic_cast<Derived*>(b); // Downcast if (d) { d->print(); // Output "Derived" } else { std::cout << "Conversion failed" << std::endl; }

In summary, C-style casts provide the most basic conversion functionality but lack type safety; static_cast offers a safer static type conversion; dynamic_cast provides the necessary runtime type checking for polymorphic conversions, ensuring safety. In actual coding, it is recommended to use static_cast and dynamic_cast to enhance code safety and maintainability.

2024年6月29日 12:07 回复

你的答案