gpt4 book ai didi

c++ - 构造函数中抽象类的默认值

转载 作者:行者123 更新时间:2023-11-28 02:19:17 25 4
gpt4 key购买 nike

我有一个类,它的构造函数看起来像

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

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

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

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

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

最佳答案

这是直接禁止的。来自 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_;
};

关于c++ - 构造函数中抽象类的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33086820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com