引用成员的初始化需要一个临时变量C ++ [英] Initialization of reference member requires a temporary variable C++

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

问题描述

struct Div
{
   int i;
   int j;
};   

class A
{
    public:
             A();
             Div& divs;
};

在我的构造函数定义中,我有以下

In my constructor definition, I have the following

A::A() : divs(NULL)
{}

我得到以下错误:

  Error72 error C2354: 
  'A::divs' : initialization of reference member requires a temporary variable


推荐答案

引用必须初始化以引用某事;它不能引用什么,所以你不能默认构造一个包含一个类(除非,如其他人建议,你定义一个全局null值)。您将需要一个赋予 Div 的构造函数:

A reference must be initialised to refer to something; it can't refer to nothing, so you can't default-construct a class that contains one (unless, as others suggest, you define a global "null" value). You will need a constructor that is given the Div to refer to:

explicit A(Div &d) : divs(d) {}

能够为null,那么你需要一个指针,而不是引用。

If you want it to be able to be "null", then you need a pointer, not a reference.

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

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