【发布时间】:2012-04-18 06:31:48
【问题描述】:
根据经验,以下工作(gcc 和 VC++),但它是有效且可移植的代码吗?
typedef struct
{
int w[2];
} A;
struct B
{
int blah[2];
};
void my_func(B b)
{
using namespace std;
cout << b.blah[0] << b.blah[1] << endl;
}
int main(int argc, char* argv[])
{
using namespace std;
A a;
a.w[0] = 1;
a.w[1] = 2;
cout << a.w[0] << a.w[1] << endl;
// my_func(a); // compiler error, as expected
my_func(reinterpret_cast<B&>(a)); // reinterpret, magic?
my_func( *(B*)(&a) ); // is this equivalent?
return 0;
}
// Output:
// 12
// 12
// 12
- reinterpret_cast 有效吗?
- C 样式转换是否等效?
- 目的是将位于
&a的位解释为 B 类,这是一种有效/最好的方法吗?
(题外话:对于那些想知道为什么我正在尝试这样做的人,我正在处理两个需要 128 位内存并使用具有不同内部结构的 C 库名称 - 很像我示例中的结构。我不想要 memcopy,也不想在 3rd 方代码中乱搞。)
【问题讨论】:
-
就我个人而言,我只是认为它相当于 c-style cast 的 c++
-
@JurajBlaho 我看到了,但上面的细微差别是我没有使用指针(在重新解释演员表中) - 这足以让我至少想仔细检查一下有效。
标签: c++