繁体   English   中英

C ++类型将int强制转换为union

[英]C++ type casting int to union

我正在将现有代码的一部分从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;
}

将主函数中的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的工作?

在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

请参见此处的工作示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM