下面列出了相关代码,您可以在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/