C++ 在构造函数中设置数组大小,复制一个二维数组

标签 c++ arrays

所以在我的类 Foo 的头文件中,我声明了一个二维整数数组,如下所示:

int board[][];

我故意遗漏了一个大小,因为我想在构造函数中设置它。 board[][] 初始化后大小不会改变。我的一个构造函数看起来像这样:

Foo(int _board[][]);

在这里,我想将 board[][] 设置为与 _board[][] 相同的大小,并复制内容。我已经尝试在 Foo 的 .cpp 实现中使用它:

Foo::Foo(int _board[][]){
board[][] = _board[][]; //Does not work as intended
}

但是,这并没有按预期工作。如何使 board[][] 与构造函数中的 _board[][] 具有相同的大小和相同的内容?

最佳答案

C++ 与 Java 不同。 int a[][]; 不允许作为变量类型。一些误导性的 C++ 特性是第一个尺寸允许留空:

int foo(int a[]);
int foo(int a[][3]); 
int foo(int a[][3][4]); 

另一个误导性的 C++ 特性是在数组的初始化中允许这样做(编译器将计算大小):

int a[][] = {{1,2}, {1,2,3,4}, {1}};

相当于:

int a[3][4] = {{1,2}, {1,2,3,4}, {1}};

对于您的情况 - 使用 std::vector:

std::vector<std::vector<int>> board;
Foo(std::vector<std::vector<int>> board) : board(board) {}

如果您出于某种原因不能使用 std::vector - 那么唯一的解决方案是使用具有两种大小的 int**:

int** board;
size_t s1;
size_t s2;
Foo(int** board = NULL, size_t s1 = 0, size_t s2 = 0) : board(board), s1(s1), s2(s2) {}

但请注意,您不能使用这种方式:

int board[][] = {{1,1,2},{1,2,2}};
Foo foo((int**)board,2,3);

因为你必须提供一个动态数组:

int** board = new int*[2] { new int[3]{1,1,2}, new int[3]{1,2,2}};

从那以后 - 你必须实现复制构造函数、赋值运算符和析构函数:

Foo(const Foo& other) : TODO { TODO }  
~Foo() { TODO }  
Foo& operator = (Foo other) { TODO }

因此,只需使用 std::vector。

关于C++ 在构造函数中设置数组大小,复制一个二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13113764/

相关文章:

c++ - Windows 8 上的 DLL LoadCount

c++ - 插入两个相互引用的 SQL 表而无需执行单独的查询?

c++ - 软阴影 : Spherical Area Light Source

c++ - Qt 更新 QGraphicsScene 中的 QPixmapItem

java - 在运行时间 O(n logn) 内比较数组的每个元素

arrays - 将向量转换为 3 维矩阵

c++ - 是否建议使用 extern 来避免 header 依赖?

C 编程数组编译时错误

c - 将字符串写入动态分配的数组

javascript - Array.toString 在循环外返回空