为什么允许将派生类的方法static_cast为基类的方法?
Why is it allowed to static_cast a method of a derived class to a method of the base class?
example
struct B1{int x; void f(){x = 1;}};
struct D : B1{int x; void f(){B1::x = 2;}};
using Dmp = void(D::*)();
using B1mp = void(B1::*)();
int main()
{
Dmp dmp = &D::f;
D d;
(d.*dmp)(); // ok
B1mp b1mp = static_cast<B1mp>(dmp); // hm, well that's weird
B1 b1;
(b1.*b1mp)();
dmp = &B1::f; // ok
}
并且此示例将编译和运行良好,不会出现任何问题。但是等等,现在我将在D::f
中使用D::x
,现在 - 任何事情都可能发生在运行时。
是的,您还可以static_cast
指向基的指针指向派生的指针。
static_cast<D*>( (B1*)0 )
但是在这里你可以使用 RTTI 来检查类型,或者如果可能的话只使用dynamic_cast
。
是的,static_cast
允许许多可能以"不安全"方式使用的东西,例如将void*
转换为另一种对象指针类型,将Base*
转换为Derived*
,以及这个。
虽然与reinterpret_cast
和const_cast
相比,static_cast
可以被认为是"相对安全"的,但它仍然是一个演员阵容。像所有强制转换一样,它表示忽略某些类型系统的安全要求的请求,然后程序员负责仔细正确地使用它。
in
void f(B *b) {
static_cast<D*>(b)->d_method();
b->static_cast<void (B::*)()>(&D::d_method)();
}
您假设b
在每种情况下都是完全相同程度的D
。 能够强制转换指向成员的指针允许调用方在传递给需要基的指针指向成员的函数时从任何派生类中指定任何函数。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 如何理解C++标准N3337中的expr.const.cast子句8
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 没有为自己的结构调用列表推回方法
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- 枚举环境变量的惯用C++14/C++17方法