如何将一个作用域中的枚举作为函数参数传递给另一个作用域?由于这失败了:
enum class L;
struct TestClass
{
void foo(L n)
{
int v = static_cast<int>(n);
int r[v] = { 9 };
cout << "\n" << v << "\n";
}
};
int main()
{
enum class L : int
{
A, B, C, D
};
TestClass main;
main.foo(L::D);
return 0;
}
error: cannot convert ‘main()::L’ to ‘L’
80 | main.foo(L::D);
| ~~~^
| |
| main()::L
如何解决这个问题(在确切的位置,而不是将枚举移动到其他范围)?
最佳答案
How to solve this (in the exact place, not move enum to a scope else)?
在作为参数传递时强制转换枚举。
main.foo(static_cast<int>(L::D));
那么你的成员函数将是
void foo(int n)
{
std::vector<int> r(n, 9); // used `std::vector` instead of VLA
std::cout << "\n" << n << "\n";
}
( See sample code )
请注意,VLA 不是标准 C++ 的一部分。请阅读以下帖子了解更多信息: Why aren't variable-length arrays part of the C++ standard?
更喜欢使用std::vector
如上面的代码示例所示。
关于c++ - 将一个作用域中的枚举作为函数参数传递给另一个作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62229895/