初始化初始化列表中的对象

waa*_*919 3 c++

我有一个class Foo我需要初始化对另一个类的引用的地方,但首先我需要从另一个类获得一些引用接口.

这只是一个虚拟代码,可以更好地解释我的两个问题:

class Foo
{
public:
  Foo();
  ~Foo();
private:
  int m_number;
  OtherClass& m_foo;
};

Foo::Foo() :
  m_number(10)
{
  // I really need to do this get's
  Class1& c1 = Singleton::getC1();
  Class2& c2 = c1.getC2();
  Class3& c3 = c2.getC3();

  //How can I put the m_foo initialization in the initialization list?
  m_foo(c3);
}
Run Code Online (Sandbox Code Playgroud)

问题是:

1 -在初始化我的成员之前,我需要检索上面的所有引用m_foo.但我想初始化m_foo初始化列表.如果没有一条线,那么最好的方法是什么.有什么办法吗?

2 -通过上面的代码,我得到错误:

error: uninitialized reference member 'OtherClass::m_foo' [-fpermissive]
Run Code Online (Sandbox Code Playgroud)

因为我正在初始化括号,因为它将在初始化列表中完成.我怎样才能m_foo正确初始化?

Jar*_*d42 8

您可以使用委托构造函数(从C++ 11开始):

class Foo
{
public:
    Foo() : Foo(Singleton::getC1()) {}

private:

    explicit Foo(Class1& c1) : Foo(c1, c1.getC2()) {}
    Foo(Class1& c1, Class2& c2) : Foo(c1, c2, c2.getC3()) {}
    Foo(Class1& c1, Class2& c2, Class3& c3) : m_number(10), m_foo(c3)
    {
        // other stuff with C1, c2, c3
    }
    // ...
};
Run Code Online (Sandbox Code Playgroud)