c++将int类型转换为联合类型

C++ type casting int to union

本文关键字:类型 类型转换 int c++      更新时间:2023-10-16

我正在将一部分现有代码从C移植到c++。我只需要将文件移动到。cc,制作并修复错误。现有的代码类似于这样,

/* a.h */
typedef union foo_ {
    int var;
}foo;
void fun(foo a)
{
   printf("%dn", a.var);
}

/* a.cc or a.c */
#include<stdio.h>
#include"a.h"
int main()
{
    int a = 0x10;
    foo x;
    x = (foo)a; // Error when the file is .cc but works with .c
    fun(x);
    return 0;
}

将main函数中的整型变量'a'强制转换为'foo'在C语言中可以正常工作,但在c++中显示以下错误,

a.cc: In function int main():
a.cc:8:14: error: no matching function for call to foo_::foo_(int&)
a.cc:8:14: note: candidates are:
a.h:2:15: note: foo_::foo_()
a.h:2:15: note:   candidate expects 0 arguments, 1 provided
a.h:2:15: note: foo_::foo_(const foo_&)
a.h:2:15: note:   no known conversion for argument 1 from int to const foo_&

它建议调用构造函数。我尝试了static_cast, reinterpret_cast和他们没有解决这个问题。我不能修改联合或函数定义。

是否有任何方法可以使此工作类似于C ?

在c++中,联合也可以使用构造函数,所以您可以为int提供一个:

union foo {
    foo() = default;
    foo(int i)
    : var(i)
    { }
    int var;
};
foo x;      // default-constructs `var`
x = (foo)a; // copy-constructors foo from a temporary 
            // constructed using foo(int ) 

或者因为这些东西是可见的:

x.var = a;

大多数情况下可以在c++中聚合构造联合:

//foo x;
//x = (foo)a; <-- Wrong
foo x = {a}; // Right