我正在将现有代码的一部分从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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句