Initialization of reference member requires a temporary variable C++

后端 未结 12 1895
自闭症患者
自闭症患者 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:23

    divs is a reference, not a pointer. You can't set it to NULL, it has to point to an actual object of some kind. The best thing to do here is probably to define a static/global instance of Div that you arbitrarily define to be the "Null Div" (set its value to something you're unlikely ever to use) and initialize div to that. Something like this:

    struct Div
    {
       int i;
       int j;
    };   
    
    Div NULL_DIV = { INT_MAX, INT_MAX };
    
    class A
    {
        public:
                 A();
                 Div& divs;
    };
    
    
    A::A() : divs(NULL_DIVS)
    {
    }
    

    Or, alternatively, just make divs a pointer instead of a reference.

    *Note that you can't use a const reference unless you cast away the constness because by default the compiler won't allow you to assign a cosnt ref to a non-const ref.

提交回复
热议问题