c++ - 无法弄清楚 int[3][3] 和 int(* const)[3] 之间的区别

标签 c++ arrays templates pointers g++

我有这个代码:

int board[3][3];        // I am ommiting initialization code for board here so as not to clutter it.
typedef std::vector<std::pair<int [3][3], int> > History;
History hist = History();
const std::pair<int[3][3], int> p = std::make_pair(board, cell);
hist.push_back(p);

但是用 g++ 编译它给了我这个我无法理解的错误:

In file included from /usr/include/c++/4.7/bits/stl_algobase.h:65:0,
                 from /usr/include/c++/4.7/vector:61,
                 from performancesystem.h:29:
/usr/include/c++/4.7/bits/stl_pair.h: In instantiation of
    ‘std::pair<_T1, _T2>::pair(const std::pair<_U1, _U2>&) [with _U1 = 
    int (*)[3]; _U2 = int; _T1 = int [3][3]; _T2 = int]’:
Test.cpp:74:65:   required from here
/usr/include/c++/4.7/bits/stl_pair.h:111:39: error: incompatible types in
    assignment of ‘int (* const)[3]’ to ‘int [3][3]’

在理解 C++ 中指针和数组之间的区别时,我总是遇到这个问题。他们不应该是同一件事吗?谁能帮帮我?

最佳答案

您的问题不是数组指针差异(很大)。

问题是数组不能在赋值中按值复制。将 C 数组包装在一个类中可以解决这个问题,或者更好 - 使用标准数组。

关于c++ - 无法弄清楚 int[3][3] 和 int(* const)[3] 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13207638/

相关文章:

html - 如何在 Golang 中设置 HTML <select> 元素的默认值?

c++ - 这个构造函数做什么?

java - Test2 数组初始化错误

c++ - 函数采用可变数量的不同类型的 initializer_lists

c++ - 无法访问 C++ 中类模板继承第二级上的 protected 类成员

php - 如何使用 php 从数组循环中获取唯一 ID

c++ - 是否可以在 C++ Actor Framework 中对类型化 actor 使用继承?

c++ - 用另一个替换 QML 文件内容

c++ - 将输出文本格式化为 .doc/.docx

javascript - 输入整数的总和