Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 重新解释的有效使用?_C++ - Fatal编程技术网

C++ 重新解释的有效使用?

C++ 重新解释的有效使用?,c++,C++,根据经验,下面的工作(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[]) {

根据经验,下面的工作(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
typedef结构
{
int w[2];
}A;
结构B
{
int blah[2];
};
作废我的职能(B)
{
使用名称空间std;

cout在C++11中,如果这两种类型是布局兼容的,则这是完全允许的,对于相同且具有标准布局的结构也是如此

您也可以将两个结构粘贴在C++的以前版本中,这保证了能够访问相同的数据成员(数据成员的“共同初始序列”),对于不同的结构类型,相同的顺序。


在此情况下,是的,C样式的CAST是等价的,但是RealTytRask可能更习惯。

我个人认为它是C++的C型可复制的@ JuraJaLaHo的副本,但上面的细微差别是我不使用指针(在重新解释的CAST中)。-这足以让我至少想再次检查它是否有效。从链接的答案来看,在C++11之前的版本中似乎不严格允许这样做,但“可能在实践中有效”。这对我来说已经足够好了!要有一个“通用的初始序列”,成员的名称也必须相同。(至少官方如此。)而g++有时会故意破坏原始帖子中的代码。这意味着标准禁止使用
union
,g++禁止使用
reinterpret\u cast