为什么引用数组是非法的? [英] Why are arrays of references illegal?

查看:30
本文介绍了为什么引用数组是非法的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码无法编译.

int a = 1, b = 2, c = 3;
int& arr[] = {a,b,c,8};

C++ 标准对此有何评论?

我知道我可以声明一个包含引用的类,然后创建该类的数组,如下所示.但我真的很想知道为什么上面的代码不能编译.

I know I could declare a class that contains a reference, then create an array of that class, as shown below. But I really want to know why the code above doesn't compile.

struct cintref
{
    cintref(const int & ref) : ref(ref) {}
    operator const int &() { return ref; }
private:
    const int & ref;
    void operator=(const cintref &);
};

int main() 
{
  int a=1,b=2,c=3;
  //typedef const int &  cintref;
  cintref arr[] = {a,b,c,8};
}

可以使用 struct cintref 而不是 const int & 来模拟引用数组.

It is possible to use struct cintref instead of const int & to simulate an array of references.

推荐答案

回答你关于标准的问题我可以引用C++标准§8.3.2/4:

Answering to your question about standard I can cite the C++ Standard §8.3.2/4:

不得有对引用的引用,没有引用数组,也不得有指向引用的指针.

There shall be no references to references, no arrays of references, and no pointers to references.

那是因为引用不是对象,不占用内存,所以没有地址.您可以将它们视为对象的别名.声明一个空数组没有多大意义.

That's because references are not objects and doesn't occupy the memory so doesn't have the address. You can think of them as the aliases to the objects. Declaring an array of nothing has not much sense.

这篇关于为什么引用数组是非法的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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