在构造函数C ++中初始化引用 [英] Initialising reference in constructor C++

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

问题描述

我不认为是一个重复的问题。有类似的,但他们不帮助我解决我的问题。



根据这个,以下内容在C ++中有效:

  class c {
public:
int&一世;
};

但是,当我这样做时,会出现以下错误:

 错误:未初始化的引用成员'c :: i'

如何成功地初始化



非常感谢。 / p>

解决方案

没有空引用这样的东西。您可在对象初始化时提供引用。将它放在构造函数的基本初始化器列表中:

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

另一种方法是 i(* new int) 要回答你的问题,你可能只是想要,但是这样做可能会非常糟糕。



< i 作为成员对象,而不是引用,所以只需说 int i; ,并将构造函数写为 c():i(0){} c(int a = 0):i(a){} 。 >

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.

解决方案

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) { }.

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

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