C ++中未初始化的引用成员 [英] Uninitialized reference member in C++

查看:2182
本文介绍了C ++中未初始化的引用成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在C ++中做类,我希望它有一个字段 Osoba& 但我得到一个奇怪的错误:

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;

    }
};


推荐答案

使用初始化列表, / p>

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;  

    }
};

这篇关于C ++中未初始化的引用成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆