gpt4 book ai didi

c++ - union 行为

转载 作者:太空宇宙 更新时间:2023-11-04 11:56:40 26 4
gpt4 key购买 nike

是否有可能从 union 中获得以下行为?

class A : public Base //Base is an abstract base class.
{
public:
A( int );
virtual void foo() //A virtual function from Base.
{
//I don't want to have to specify if it's oneOption or twoOption.
// I would like it to just call whichever one's is defined in mData.
mData.foo();
}
private:
union B
{
C oneOption; //A class which inherits from Base.
D twoOption; //Another class which inherits from Base.
} mData;
};

基本上,我想要一个包含派生类 union 的类。然后我想根据我的 Union 实现所有虚函数基类。

如果它太令人困惑,我可以尝试重新措辞。

谢谢

最佳答案

union 成员不允许有构造函数。

你可以这样做:

void PickC() { new (oneOption) C; }
void PickD() { new (twoOption) D; }
C * GetC() { return (C*) oneOption; }
D * GetD() { return (D*) twoOption; }

private:

union B
{
char oneOption[ sizeof(C) ]; //A class which inherits from Base.
char twoOption[ sizeof(D) ]; //Another class which inherits from Base.
} mData;

但它真的很丑。

关于c++ - union 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15961901/

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