引用成员的初始化需要一个临时变量 C++

2021-12-23 00:00:00 reference struct c++
struct Div
{
   int i;
   int j;
};   

class A
{
    public:
             A();
             Div& divs;
};

在我的构造函数定义中,我有以下内容

In my constructor definition, I have the following

A::A() : divs(NULL)
{}

我收到以下错误:

  Error72 error C2354: 
  'A::divs' : initialization of reference member requires a temporary variable 

推荐答案

必须初始化引用才能引用某事;它不能引用任何内容,因此您不能默认构造一个包含一个类的类(除非像其他人建议的那样,您定义了一个全局空"值).您将需要一个带有 Div 的构造函数来引用:

A reference must be initialised to refer to something; it can't refer to nothing, so you can't default-construct a class that contains one (unless, as others suggest, you define a global "null" value). You will need a constructor that is given the Div to refer to:

explicit A(Div &d) : divs(d) {}

如果您希望它能够为null",那么您需要一个指针,而不是一个引用.

If you want it to be able to be "null", then you need a pointer, not a reference.

相关文章