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

查看:17
本文介绍了引用成员的初始化需要一个临时变量 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 

推荐答案

必须初始化引用才能引用某事;它不能引用任何内容,因此您不能默认构造一个包含一个类的类(除非像其他人建议的那样,您定义了一个全局空"值).您将需要一个带有 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天全站免登陆