2

首先,如果这是一个糟糕的问题,我深表歉意。我是 C++ 新手。

我有一组包含引用类型字段的类头,它是一个接口(由纯虚函数构建的类)。我想初始化我的类,以便默认情况下将引用类型字段设置为某个“具体”派生类,这是使用默认构造函数(无参数!)完成的。我还希望能够用另一个“具体”派生类覆盖这个初始化。

到目前为止,我的类标题如下:

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 字段执行此操作,并且将超出构造函数的范围),我会将其标记为接受的答案。或者将其标记为适当的副本。

4

1 回答 1

2

您可以在类中添加默认对象,例如:

class Foo {
public:
    Foo() : bar(defaultBar);{}
    Foo(IBar& bar) : bar(bar) {}

protected:
    const BarDerivedA defaultBar; // Before the reference.
    const IBar& bar;
};
于 2015-02-23T10:41:26.070 回答