c++ - 是否可以通过初始化列表初始化引用类型?

标签 c++ windows visual-studio-2013 initialization-list

首先,如果这是一个糟糕的问题,我深表歉意。我是 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/

相关文章:

Windows 上带有 Docker 的 Linux 内核与 WSL Linux 内核不匹配

windows - 在 Windows 上的 bash 中清除 PowerShell 控制台

c++ - 如何在 Visual Studio Express 2013 中使用 C++ <文件系统>?

image - 如何在不加载图像的情况下获取图像的尺寸

c++ - C++ 中 const list<t> 的迭代器

c++ - 为什么 clang 不像 #define 那样优化全局常量?

windows - 我可以在 Emacs 的 shell 模式下使用 PowerShell 吗?

visual-studio - 如何暂时禁用 LocalDB 数据库以进行连接失败测试?

c++ - 为什么 "most important const"必须是 const?

C++ 超出下标范围