在构造函数 C++ 中初始化引用

2021-12-30 00:00:00 constructor c++

我不认为这是一个重复的问题.有类似的,但它们并没有帮助我解决我的问题.

I don't think is a duplicate question. There are similar ones but they're not helping me solve my problem.

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

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'

如何在构造上成功初始化i=0?

How can I initialise successfully do i=0on construction?

非常感谢.

推荐答案

没有空引用"这样的东西.您必须在对象初始化时提供参考.把它放在构造函数的基本初始化列表中:

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;
};

另一种选择是 i(*new int),但这会很糟糕.

An alternative would be i(*new int), but that'd be terrible.

为了回答您的问题,您可能只想将 i 设为成员对象,而不是引用,所以只需说 int i;,并将构造函数编写为 c() : i(0) {}c(int a = 0) : i(a) { }.

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

相关文章