Uninitialized reference member in C++

*爱你&永不变心* 提交于 2019-12-10 15:54:07

问题


I have made class in C++ and I wanted it to have a field Osoba& but I get an weird error:

class Rachunek{
public:
    Osoba& wlasciciel;
    double stan_konta;
    Rachunek(Osoba* wlasciciel, double stan_konta){ //Uninitialized reference member
        this->wlasciciel = wlasciciel;
        this->stan_konta = stan_konta;

    }
};

回答1:


Use initializing list like this: (Best approach)

class Rachunek{
public:
    Osoba& wlasciciel;
    double stan_konta;
    Rachunek(Osoba* wlasciciel, double stan_konta): 
        wlasciciel(*wlasciciel) , 
        stan_konta(stan_konta)  { //Uninitialized reference member


    }
};

You have a reference as a member and a reference must be initialized right away. This notation allows for initialization at declaration time. If you instead used a normal member without & it would work fine as you did it. Though the presented style here is more efficient.

Alternativly: (Lesser efficient approach)

class Rachunek{
public:
    Osoba wlasciciel; // Note missing & on the type. 
    double stan_konta;
    Rachunek(Osoba* wlasciciel, double stan_konta)
    {
        this->wlasciciel = *wlasciciel;  
        this->stan_konta = stan_konta;  

    }
};



回答2:


You need to use the constructor initialization list

Rachunek(Osoba* wlasciciel, double stan_konta)
      :wlasciciel (*wlasciciel)
      ,stan_konta (stan_konta)
{ 
}

It is obvious from your code that you lack a lot of basic C++ knowledge, which is fine, but please do refer to a good book



来源:https://stackoverflow.com/questions/16634181/uninitialized-reference-member-in-c

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