构造函数隐式删除

约翰

相关代码在下面列出,您可以在https://godbolt.org/z/3GH8zD上进行检查我确实可以解决complier的编译错误。但是我不清楚它背后的原因。我很乐意为这个问题提供帮助。

struct A
{
    int x;
    A(int x = 1): x(x) {} // user-defined default constructor
};

struct F : public A
{
    int& ref; // reference member
    const int c; // const member
    // F::F() is implicitly defined as deleted
};

int main()
{
  F f; // compile error
}

编译器抱怨:

Could not execute the program

Compiler returned: 1

Compiler stderr

<source>:10:15: error: declaration does not declare anything [-fpermissive]

   10 |         const int; // const member

      |               ^~~

<source>: In function 'int main()':

<source>:16:9: error: use of deleted function 'F::F()'

   16 |       F f; // compile error

      |         ^

<source>:7:12: note: 'F::F()' is implicitly deleted because the default definition would be ill-formed:

    7 |     struct F : public A

      |            ^

<source>:7:12: error: uninitialized reference member in 'struct F'

<source>:9:14: note: 'int& F::ref' should be initialized

    9 |         int& ref; // reference member

      |              ^~~

正确的代码可能是:

struct F
{
    int& ref = x; // reference member
    const int c = 1; // const member
    // F::F() is implicitly defined as deleted
};
拔示巴

创建类型的对象时,类成员int& ref需要绑定intF

编译器生成的默认构造函数不知道如何绑定它,因此编译器仅删除默认构造函数。

在第二个片段中,您明确设置了成员。(您可以从C ++ 11做到这一点)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

构造函数异常和隐式删除

调用隐式删除的默认构造函数

隐式与显式删除副本构造函数

gmock调用到隐式删除的副本构造函数

隐式构造函数与“空”构造函数

默认构造函数与隐式构造函数

Scala隐式构造函数

如果删除复制构造函数,是否没有隐式move构造函数?

为什么对隐式和显式删除的move构造函数进行不同的处理?

通过方法/构造函数参数隐式与隐式使用

模板推导和隐式构造函数

C++ 构造函数隐式成员

如何从构造函数传递隐式引用

隐式转换和复制构造函数

C ++构造函数隐式类型转换

隐式调用复制构造函数?

实例模拟和隐式构造函数

用户定义的构造函数和隐式默认构造函数

为什么你会 =delete 隐式删除默认构造函数,重点是什么?

为什么(已删除)副本构造函数比隐式转换更可取?

隐式删除的副本构造函数编译错误,返回的指针值

错误:使用auto调用unique_ptr的隐式删除副本构造函数

尝试将参数传递给方法时出现“调用隐式删除的副本构造函数”错误

为什么类中的ostringstream类型的成员导致“调用隐式删除的复制构造函数”错误?

显式默认的默认构造函数被隐式删除,因为 unordered_map 与结构一起用作键

隐式与显式默认构造函数调用

C ++ 11:默认构造函数:隐式还是显式?

C ++隐式和显式继承构造函数调用

隐式定义与显式声明的构造函数