构造函数初始化命名的联合成员

时间:2013-10-04 21:38:09

标签: c++

此代码无法编译。我得到“预期{或”,指的是。 (Xcode 5,所以它是一个相当完整的C ++ 11编译器。)

有没有办法在构造函数初始化列表中初始化嵌套联合的成员,还是只需要在构造函数体中执行它?

class Foo
{
public:
    Foo(): m_bar.m_x(123) { }
private:     // ^ error here
    union
    {
        union
        {
            int m_x;
            float m_y;
        }
        m_pod;
        std::string m_name;
    };
};

1 个答案:

答案 0 :(得分:8)

以下是修复各种问题的代码的重写版本:

  1. 它为嵌套的union提供了一个构造函数:与任何其他类类型一样,如果你不想单独初始化它们,union需要一个构造函数。
  2. 它给嵌套的union bar一个析构函数,因为它的析构函数是delete d,否则会由于std::string成员(并且它需要处理成员的情况)可能是std::string类型,此代码不是。标准中的相关条款是12.4 [class.dtor]第5段:

      

    如果出现以下情况,则将类X的默认析构函数定义为已删除:

    - X is a union-like class that has a variant member with a non-trivial destructor,
    - ...
    
  3. 它还包含缺少的标题<string>
  4. 这是代码:

    #include <string>
    class Foo
    {
    public:
        Foo(): m_bar(123) { }
    private:
        union bar
        {
            bar(int x): m_pod(x) {}
            bar(float y): m_pod(y) {}
            ~bar() {}
            union baz
            {
                baz(int x): m_x(x) {}
                baz(float y): m_y(y) {}
                int m_x;
                float m_y;
            }
            m_pod;
            std::string m_name;
        } m_bar;
    };