【问题标题】:Initialize object in initializer list在初始化列表中初始化对象
【发布时间】:2015-09-15 19:43:04
【问题描述】:

我有一个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);
}

问题是:

1 - 在初始化我的成员 m_foo 之前,我需要检索上述所有引用。但我想在初始化列表中初始化m_foo。什么是最好的方法来实现这一点,而不是在一行中。 有什么办法吗?

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

error: uninitialized reference member 'OtherClass::m_foo' [-fpermissive]

因为我使用括号进行初始化,就像在初始化列表中一样。我怎样才能正确初始化m_foo

【问题讨论】:

  • c1c2c3 是否用于其他用途?
  • @NathanOliver:我认为 OP 对此非常清楚:是的! “我真的需要这样做”
  • @Waggili 在哪里?他只是说在初始化m_foo之前需要它们
  • @waas1919 你说的是member initializer lists 而不是initializer_lists,我建议修改你的标题以明确这一点。

标签: c++


【解决方案1】:

您可以使用委托构造函数(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
    }
    // ...
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    • 2013-06-27
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    相关资源
    最近更新 更多