c++ - 转换为具有相同基数 : 的类

标签 c++ casting

考虑以下示例:

#include <iostream>

struct A{ void foo(){ std::cout << "foo()" << std::endl; } };

struct D{ void bar(){ std::cout << "bar()" << std::endl; } };

struct B : A, D{ };

struct C : A{ };

B *b = new B();

C *c = reinterpret_cast<C*>(b);

int main(){ c -> foo(); } //prints foo

DEMO

它有效,但我不确定我是否在这里得到了某种 UB。也许有人可以引用标准?

我提供这种情况是因为我有两个类(BC)并且在某些模块中我只需要使用 B 的一部分> 的功能(C 的功能)。但是我已经实例化了 B 类,我可以像我一样制作 reinterpret_cast 吗?

最佳答案

这不是 reinterpret_cast 的目的。

大多数在线文档都有类似于

的免责声明

Misuse of the reinterpret_cast operator can easily be unsafe. Unless the desired conversion is inherently low-level, you should use one of the other cast operators.

The reinterpret_cast operator can be used for conversions such as char* to int*, or One_class* to Unrelated_class*, which are inherently unsafe.

此节选自MSDN .强调我的。

关于c++ - 转换为具有相同基数 : 的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29448033/

相关文章:

android - Qt 不检测 Android NDK

iphone - 简单 : NSArray object to Double?

postgresql - PostgresQL。与在 WHERE 子句中显式定义整个时间戳相比,将时间戳转换为日期的区别

c++ - 堆栈上声明的变量的发送地址?

c++ - Qt5 QuickView 无法创建窗口 : no screens are available

c++ - 具有共线点的礼品包装算法

java - 通过括号转换为字符串会导致 Android 崩溃

javascript - Angular $routeParams 强制变量类型

javascript - 寻找一行类型转换 Number(oldValue) += 1;在JS中

c++ - 魔方程序(C++)