How to initialize the reference member variable of a class?

后端 未结 2 1913
名媛妹妹
名媛妹妹 2020-12-06 17:56

Consider the following code C++:

    #include

using namespace std;

class Test {
    int &t;
public:
    Test (int &x) { t = x;          


        
2条回答
  •  失恋的感觉
    2020-12-06 18:41

    My compiler emits this error:

    error C2758: 'Test::t' : must be initialized in constructor base/member initializer list

    And that's exactly what you must do. References must be initialized in the initializer list:

    #include
    
    using namespace std;
    
    class Test {
        int &t;
    public:
        Test (int &x) : t(x) {  } // <-- initializer list used, empty body now
        int getT() { return t; }
    };
    
    int main()
    {
        int x = 20;
        Test t1(x);
        cout << t1.getT() << " ";
        x = 30;
        cout << t1.getT() << endl;
        return 0;
    }
    

    Explanation:

    If the reference is not in the initiliazer list, it's next to impossible for the compiler to detect if the reference is initialized. References must be initialized. Imagine this scenario:

    Test (int &x, bool b) 
    {
       if( b ) t = x;
    }
    

    Now it would be up to the caller of the constructor to decide if valid code was generated. That cannot be. The compiler must make sure the reference is initialized at compile time.

提交回复
热议问题