相关代码在下面列出,您可以在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
需要绑定到。int
F
编译器生成的默认构造函数不知道如何绑定它,因此编译器仅删除默认构造函数。
在第二个片段中,您明确设置了成员。(您可以从C ++ 11做到这一点)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句