Initialization of reference member requires a temporary variable C++

后端 未结 12 1875
自闭症患者
自闭症患者 2020-12-10 03:29
struct Div
{
   int i;
   int j;
};   

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

In my constructor definition, I have

相关标签:
12条回答
  • 2020-12-10 04:10

    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) {}
    

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

    0 讨论(0)
  • 2020-12-10 04:12

    For one, you can't have a NULL reference. As second, all variable references in a class must be initialized at construction time.

    0 讨论(0)
  • 2020-12-10 04:13

    Plain and simple:

    A reference can never be NULL.

    0 讨论(0)
  • 2020-12-10 04:13
    class A
    {
        Div & ref(Div div) { return div; }
        public:
           A() : divs(ref(Div())) {};
           Div& divs;
    };
    
    0 讨论(0)
  • 2020-12-10 04:16

    As noted in other posts, references (Div&) cannot be null. So the most straightforward change you can make is to provide a reference in the constructor and initialize your reference member. Like this,

    class A
    {
        public:
                 A(Div& inDivs);
                 Div& divs;
    
    };
    
    public A::A( Div& inDivs )
    : divs( inDivs )
    {}
    
    0 讨论(0)
  • 2020-12-10 04:18

    References have to reference something. There is no such thing as a null reference in the C++ language. If the member may not have a value, then it should be a pointer, or a boost::optional or some type like that.

    A reference must be initialized to reference a valid object.

    0 讨论(0)
提交回复
热议问题