工会的行为

Union Behaviour

本文关键字:      更新时间:2023-10-16

是否有可能从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;
};

基本上,我想有一个类包含派生类的联合。然后我想实现所有的虚函数基类在我的联合。

如果太让人困惑的话,我可以试着重新表述一下。

谢谢

联合的成员不允许有构造函数。

你可以这样做:

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;

从技术上讲你可以,语法是正确的,编译器会让你像你期望的那样对待两个实例变量(与一般应用于联合的约束相同)。

在实践中,当存在互斥时似乎没有必要,您可以轻松地使用指向实例的指针:

CommonAncestor *mData;

我可以看到许多可维护性问题,通过使用在语言中不存在多态性时使用的结构。

相关文章:
  • 没有找到相关文章