使用中间结果初始化多个属性
Using an intermediate result to initialise several attributes
我有一个类,其构造函数大致是这样做的:
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
。但这是一个问题,因为我需要在计算b
和c
之前构建d
。
一种方法是:
A(istream& input):b(D(input)),c(D(input)){}
但是建造一个D
(非常)昂贵(*)
有什么干净的方法可以解决这个问题?
(*)另一个问题是,如果b
和c
需要从同一个实例构建(如D
的构造函数是随机的或其他)。但这不是我的情况。
在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)
{
}
};
相关文章:
- 类的C++属性似乎已重新初始化
- 我的子类的属性是延迟初始化的
- 如何在不知道属性具有哪些构造函数的情况下初始化属性?
- boost::spirit指针属性是用nullptr初始化的吗?
- C++ 中常量属性的初始化构造函数错误
- 在构造函数 c++ 中初始化属性时出现问题
- 初始化类C++私有属性(值/引用/静态)
- 为什么结构属性声明和初始化顺序的行为是这样的?
- 程序在没有输入的情况下退出,它有基本的,驱动的类属性初始化问题
- 提升捆绑属性:是否需要初始化每个边的所有属性?
- 当我初始化了指针属性 allready 时,如何将 QGraphicsItem 向下投射到创建的类?
- 使初始化变量可供多个属性初始化方法访问
- 如何在C++中初始化孙子的祖父母(const)属性?
- 如果第二个属性未支撑,则将与支撑初始化器配对缩小转换
- 组合框初始化错误:无法读取未定义的属性'constructor'
- 正在使用std::string初始化istream属性
- QObject 自定义属性何时从样式表中指定的值初始化
- 是否可以在初始化列表中使用基类属性
- 在c++中查找对象的未初始化属性
- C++字符串上的静态属性初始化错误