c++将int类型转换为联合类型
C++ type casting int to union
我正在将一部分现有代码从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++中,联合也可以使用构造函数,所以您可以为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
相关文章:
- 哪些类型可以转换为std::any
- 基于返回类型的转换和过载扣除
- C++如何乘以包含 std::variant 元素的向量的迭代器?正在执行迭代器类型的转换?
- C++:将模板类型 char 转换为 std::string
- 由于类型从 C 转换为 C++,无法编译错误 C2440
- 在 Rcpp 中的字符串类型之间转换时出错
- C++隐式构造函数转换,后跟类型向上转换
- LLVM 无法将数组类型强制转换为常量数组
- 另一个:从"常量类型*"到"类型*"的转换无效
- 在不同类型之间转换常量指针
- C++可变参数模板类型筛选转换
- C++类型强制转换指向常量变量的指针
- 如何定义从标准类型到用户定义类型的转换?
- 编译错误 QT - 无法从类型强制转换
- 将模板类型名称转换为 uint64
- 为什么类型可转换性C++不传递
- 是否可以使用元编程将类型列表转换为对列表中每种类型具有特定隐式转换行为的新类型?
- 如何处理警告:从较小的整数类型int转换为int*
- 在函数指针类型之间转换
- Linux 编译错误 - 无法将类型"字符串"转换为类型"字符串&&"