我需要创建两个对数组的引用,这两个引用可以引用同一个数组。我尝试了以下方法:
extern int (&a)[];
extern int (&b)[];
int main()
{
b = a; // error: array type 'int []' is not assignable
}
有没有办法在 C++ 中做到这一点?
最佳答案
两件事:第一 arrays不能出现在赋值运算符的左侧。 cppreference 可能直接从标准中获取其文本,特别是:
§ 8.3.4
5 Objects of array types cannot be modified, see 3.10.
此外,如 cppreference 所说,数组是左值:
§ 3.10
1 Expressions are categorized according to the taxonomy in Figure 1. — An lvalue (so called, historically, because lvalues could appear on the left-hand side of an assignment expression) designates a function or an object.
尽管标准明确表示数组类型的对象不能被修改,因此得出结论数组(对象)不能出现在赋值运算符的左侧。
其次,如果您这样做编译器可能不会报错:
int a = 50, c = 42;
int& b = a;
b = c;
b = 80;
std::cout << a << " " << c; // 80 42
你会看到c
保持不变。请引用parashift C++-faq .
[8.5] How can you reseat a reference to make it refer to a different object?
No way.
You can't separate the reference from the referent.
Unlike a pointer, once a reference is bound to an object, it can not be "reseated" to another object. The reference itself isn't an object (it has no identity; taking the address of a reference gives you the address of the referent; remember: the reference is its referent).
关于c++ - 数组类型不可赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25987133/