gpt4 book ai didi

c++ - 访问 Union 内部的类(class)

转载 作者:行者123 更新时间:2023-11-28 05:17:03 26 4
gpt4 key购买 nike

我在第三方库中有类 A 的声明,所以我无法修改它。我需要使用类 B 的声明将其传递给方法,有没有办法在不修改类 A 的情况下做到这一点?/p>

当我尝试这样做时:

#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

Live Example!

我的假设是它发生是因为 B 位于未命名的命名空间中。

PS: 如果我可以修改 union 的声明来自:

union {...

到:

union T {...

这将通过以下方式简单地完成:

A::T::B test;

最佳答案

您可以使用decltype 获取 union 的类型,然后您可以访问B:

decltype(std::declval<A&>().un)::B test;

coliru example

关于c++ - 访问 Union 内部的类(class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42420850/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com