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

ter*_*ory 0 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;
    };
};
Run Code Online (Sandbox Code Playgroud)

Die*_*ühl 10

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

  1. 它给出了嵌套的unionsa构造函数:与任何其他类类型一样,union如果您不想单独初始化它们,则需要构造函数.
  2. 它给嵌套union bar的析构函数,因为它的析构函数是否delete由于其他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,
    - ...
    
    Run Code Online (Sandbox Code Playgroud)
  3. 它还包括缺少的标题<string>.

这是代码:

#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;
};
Run Code Online (Sandbox Code Playgroud)