构造函数隐式删除

Joh*_*ohn 7 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
}
Run Code Online (Sandbox Code Playgroud)

编译器抱怨:

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

      |              ^~~
Run Code Online (Sandbox Code Playgroud)

正确的代码可能是:

struct F
{
    int& ref = x; // reference member
    const int c = 1; // const member
    // F::F() is implicitly defined as deleted
};
Run Code Online (Sandbox Code Playgroud)

Bat*_*eba 4

当创建类型的对象时,int& ref需要将类成员绑定到 an 。intF

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

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