C ++类型将int转换为union

时间:2015-07-06 15:52:30

标签: c++ c casting

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

/* a.h */
typedef union foo_ {
    int var;
}foo;

void fun(foo a)
{
   printf("%d\n", 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函数中的int变量'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?

2 个答案:

答案 0 :(得分:5)

在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;

答案 1 :(得分:2)

您可以在大多数情况下使用C ++聚合构造联合:

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

有关工作示例,请参阅here