访问 Union 内部的 class
Access to class inside Union
我在第三方库中有class A
的声明,所以我不能修改它。
我需要使用 class B
的声明将其传递给方法,有没有办法在不修改 class A
的情况下做到这一点?
当我尝试这个时:
#include <iostream>
using namespace std;
class A
{
public:
union {
class B
{
public:
int x;
};
}un;
};
void foo(A::B & test)
{
}
int main() {
A::B test;
test.x=10;
cout << test.x << endl;
return 0;
}
我收到错误:
error: B
is not a member of A
我的假设是它发生是因为 B
在未命名的命名空间中。
PS: 如果我可以修改 union
的声明
来自:
union {...
至:
union T {...
这将通过以下方式简单地完成:
A::T::B test;
您可以使用 decltype
获取联合的类型,然后您可以访问 B
:
decltype(std::declval<A&>().un)::B test;
我在第三方库中有class A
的声明,所以我不能修改它。
我需要使用 class B
的声明将其传递给方法,有没有办法在不修改 class A
的情况下做到这一点?
当我尝试这个时:
#include <iostream>
using namespace std;
class A
{
public:
union {
class B
{
public:
int x;
};
}un;
};
void foo(A::B & test)
{
}
int main() {
A::B test;
test.x=10;
cout << test.x << endl;
return 0;
}
我收到错误:
error:
B
is not a member ofA
我的假设是它发生是因为 B
在未命名的命名空间中。
PS: 如果我可以修改 union
的声明
来自:
union {...
至:
union T {...
这将通过以下方式简单地完成:
A::T::B test;
您可以使用 decltype
获取联合的类型,然后您可以访问 B
:
decltype(std::declval<A&>().un)::B test;