c++ - 构造函数隐式删除

标签 c++ constructor

下面列出了相关代码,您可以在https://godbolt.org/z/3GH8zD上查看。 我确实可以解决编译器编译错误。但我不完全清楚其背后的原因。我将不胜感激对这个问题有一些帮助。

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
};

最佳答案

F 类型的对象为创建。

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

在第二个片段中,您显式设置了成员。 (您可以从 C++11 中执行此操作)。

关于c++ - 构造函数隐式删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62187633/

相关文章:

c++ - MPI_Irecv 没有收到循环后发送的消息

c++ - 如何读取分隔文件的最后一行

c++ - Cimg 随机抛出 CImgIOException

C++ boost属性树获取值

javascript - 如何使用参数创建对象的属性,而不必使每个属性相等

Java子类实现强制构造函数

c# - 为什么向我的实体模型类添加无参数构造函数在这里起作用?有什么影响?

c++ - Webbrowser Active X 自定义动态 MIME 处理程序 pdf

Java:使用不同的构造函数

c# - 如何从 C# XML 注释中引用构造函数?