构造函数中抽象 class 的默认值

Default value for abstract class in constructor

我有一个 class 其构造函数看起来像

class foo
{
public:
foo(Base const& b);
private:
derived c;
Base const& b_;
};

我希望 c 成为构造函数的默认值,例如

foo(Base const& b = c):b_(b)

但是我收到一条错误消息: 非静态成员引用必须相对于特定对象

如何为 b 设置特定派生 class 的默认值?

这是直接禁止的。来自 n3337:

§8.3.6/9 Similarly, a non-static member shall not be used in a default argument, even if it is not evaluated, unless it appears as the id-expression of a class member access expression (5.2.5) or unless it is used to form a pointer to member (5.3.1).

换句话说,要使其工作,c 必须是 static,因为不需要任何对象来访问静态数据成员。

class foo
{
public:
foo(Base const& b = c);
private:
static derived c;
Base const& b_;
};