1

我有一个类,其构造函数大致执行以下操作:

class B;
class C;
class D;  

class A{
private:
  B b;
  C c;

public:
  A(istream& input){
    D d(input) // Build a D based on input
    b = B(d);  // Use that D to build b
    c = C(d);  // and c
  }
}

只要具有默认构造函数B,它就应该可以正常工作。C

我的问题是B没有,所以我需要b在初始化列表中进行初始化。但这是一个问题,因为我需要先构建d,然后才能计算bc.

一种方法是:

A(istream& input):b(D(input)),c(D(input)){}

但是建造一个D(非常)昂贵的(*)

解决这个问题的干净方法是什么?


(*) 另一个问题是如果b并且c需要从同一个实例构建(例如 ifD的构造函数是随机的或其他)。但这不是我的情况。

4

1 回答 1

4

在 C++11 中,您可以使用委托构造函数

class B;
class C;
class D;

class A
{
private:

    B b;
    C c;

public:

    explicit A(istream& input)
        :
        A(D(input))
    {
    }

    // If you wish, you could make this protected or private
    explicit A(D const& d)
        :
        b(d),
        c(d)
    {
    }
};
于 2013-03-01T14:21:30.577 回答