以下代码无法编译。
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/