How to initialize the reference member variable of a class?

后端 未结 2 1921
名媛妹妹
名媛妹妹 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:33

    That is because references can only be initialized in the initializer list. Use

    Test (int &x) : t(x) {}
    

    To explain: The reference can only be set once, the place where this happens is the initializer list. After that is done, you can not set the reference, but only assign values to the referenced instance. Your code means, you tried to assign something to a referenced instance but the reference was never initialized, hence it's not referencing any instance of int and you get the error.

提交回复
热议问题