c++ - 数组类型不可赋值

标签 c++ arrays

我需要创建两个对数组的引用,这两个引用可以引用同一个数组。我尝试了以下方法:

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/

相关文章:

c++ - 如何在不在 .h 文件中制作原型(prototype)的情况下将 Objective-C++ 类公开给 swift

c++ - `std::random_device` 和 `std::mt19937_64` 和有什么区别?

c++ - Lexical_cast 抛出异常

javascript - AngularJs - 检查数组对象中是否存在值

java - 数组引用解释

c++ - 需要帮助来理解错误消息

C++ 指针损坏?

java - 使用 .equals() 比较字符串数组的两个元素

java - JTable:添加一维数组作为行

javascript - Angular - 如何根据数组中的值检查复选框?