首先,如果这是一个糟糕的问题,我深表歉意。我是 C++ 新手。
我有一组包含引用类型字段的类头,它是一个接口(interface)(由纯虚函数构建的类)。我想初始化我的类,以便默认情况下将引用类型字段设置为某个“具体”派生类,这是使用默认构造函数(无参数!)完成的。我还希望能够用另一个“具体”派生类覆盖此初始化。
到目前为止,我的类头如下:
class Foo {
public:
Foo();
Foo(IBar & bar);
protected:
/* Update 1: const field */
const IBar & bar;
...
}
但我正在为实现而苦苦挣扎:
/* Is it possible to create the reference type through the initialisation list? */
/* Update 2: corrected initialisation of bar field from "BarDerivedA() bar" to "BarDerivedA()" */
Foo::Foo()
: bar(BarDerivedA())
{
}
/* Override */
Foo::Foo(IBar & bar)
: bar(bar)
{
}
更新
我们发现使用这种潜在的设计不会有效率。 const IBar & bar
的默认值对于每个具有该字段的类几乎总是相同的对象,除了单元测试 - 我们希望能够根据需要交换模拟类。
我不想不断地在堆栈上创建相同的对象,因此将在工厂中为这些对象组工作。
我已经沿着单个构造函数的路线走下去了,如下所示:
Foo::Foo(IBar & bar)
: bar(bar)
{
}
如果有人想就初始化列表中临时对象的类引用字段设置提供适当的答案(即只能对 const 字段执行此操作,并且会超出构造函数之外的范围)我将标记它作为公认的答案。或者将其标记为适当的拷贝。
最佳答案
您可以在类中添加默认对象,例如:
class Foo {
public:
Foo() : bar(defaultBar);{}
Foo(IBar& bar) : bar(bar) {}
protected:
const BarDerivedA defaultBar; // Before the reference.
const IBar& bar;
};
关于c++ - 是否可以通过初始化列表初始化引用类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28666489/