Initialising reference in constructor C++

可紊 提交于 2019-12-17 07:30:12

问题


I don't think is a duplicate question. There are similar ones but they're not helping me solve my problem.

According to this, the following is valid in C++:

class c {
public:
   int& i;
};

However, when I do this, I get the following error:

error: uninitialized reference member 'c::i'

How can I initialise successfully do i=0on construction?

Many thanks.


回答1:


There is no such thing as an "empty reference". You have to provide a reference at object initialization. Put it in the constructor's base initializer list:

class c
{
public:
  c(int & a) : i(a) { }
  int & i;
};

An alternative would be i(*new int), but that'd be terrible.

Edit: To maybe answer your question, you probably just want i to be a member object, not a reference, so just say int i;, and write the constructor either as c() : i(0) {} or as c(int a = 0) : i(a) { }.




回答2:


A reference must be initialised to refer to something.

int a;
class c {
public:
   int& i;
   c() : i (a) {};
};



回答3:


Apart from the sweet syntax, a key feature of references is that you are pretty sure that it always point to a value (No NULL value).

When designing an API, it forces user to not send you NULL. When consuming an API, you know without reading the doc that NULL is not an option here.




回答4:


References have to be initialized upon creation. Thus you have to initialize it when the class is created. Also you have to provide some legal object to reference.

You have to use the initializer in your constructor:

class c {
public:
   c(const int& other) : i(other) {}
   int& i;
};



回答5:


Reference should be initialised either by passing data to constructor or allocate memory from heap if you want to initialize in default constructor.

class Test  
{  
    private:
        int& val;  
        std::set<int>& _set;  
    public:  
        Test() : val (*(new int())),  
                _set(*(new std::set<int>())) {  }  

        Test(int &a, std::set<int>& sett) :  val(a), _set(sett) {  }  
};  

int main()  
{  
    cout << "Hello World!" << endl;  
    Test obj;  
    int a; std::set<int> sett;  
    Test obj1(a, sett);  
    return 0;  
}

Thanks




回答6:


template<class T>
class AVLNode {

private:
       T & data;
public:
       AVLNode(T & newData) {
            data = newData;
        }
};


来源:https://stackoverflow.com/questions/6576109/initialising-reference-in-constructor-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!