c++ - 为什么引用数组是非法的?

标签 c++ arrays reference

以下代码无法编译。

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

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

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

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 & 来模拟引用数组。

最佳答案

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

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

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

关于c++ - 为什么引用数组是非法的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1164266/

相关文章:

c++ - Metro C++/XAML ListView 捕捉项

java - Java 中带有自定义对象的 Arraylist 与 Array

arrays - 如何将已排序的表索引作为字符串返回?

c++ - 为什么 const 方法不能返回非常量引用?

c++ - 清理cpp中的密码字符串

C++ 过剩速度?

c++ - 测试程序的架构/设计建议

javascript - 在事先不知道键的情况下将项目推送到对象中的数组

C 中的交叉引用结构

c++ - [] C++中get和set操作的运算符重载