Must a reference type be initialized in constructor initialization list?

前端 未结 3 692
夕颜
夕颜 2020-12-06 12:50

As self-exercise, I have written this simple code:

#include 

int gIndex = 3;

template  class Array
{
public:
    explicit Ar         


        
3条回答
  •  温柔的废话
    2020-12-06 13:12

    Must any class-member reference type be initialized in the constructor initialization list?

    Yes.

    Is that related somehow to the fact that a reference type can never be reassigned?

    Yes, plus the fact that there is no "null" or default construction for a reference. It is an alias for another object, and it has to be bound to it from the outset. You cannot do this (this is not inside a class definition):

    int main()
    {
      int& iref; // ERROR
      int i = 42;
      int& iref2 = i; // OK
    }
    

    because iref must alias something.

提交回复
热议问题