C++ 复制指针

标签 c++ arrays pointers chess

您好,我想知道如何将 C++ 中的二维数组指针的内容复制到另一个位置并设置另一个指向它的指针,这样当我对复制的指针进行更改时,原始数据不会发生任何变化?

基本上它是一个指向棋盘上棋子的数组指针。所以它就像 Piece * oldpointer = board[8][8]。现在我想复制这个指针中的所有内容,包括 Pieces 头文件中的 getvalue()、getcolor() 等方法到另一个位置,并设置指向它的指针,以便我可以进行操作在那里测试它而不必影响这个原始数据?我在某处读到我必须使用 allocate() 但我不确定。请帮忙

最佳答案

在 C++ 中,您可以按如下方式定义二维数组类型(您需要现代 C++ 编译器):

#include <array>
typedef std::array<std::array<Piece, 8>, 8> board_t;

如果你的编译器不支持 std::array 你可以使用 boost::array相反:

#include <boost/array.hpp>
typedef boost::array<boost::array<Piece, 8>, 8> board_t;

现在你可以使用上面的类型了。如我所见,您需要复制指针指向的对象:

board_t* oldpointer = new board_t;

// do some with oldpointer

// now make a copy of the instance of the object oldpointer points to
// using copy-constructor
board_t* newpointer = new board_t( *oldpointer );
// now newpointer points to the newly created independent copy

// do more

// clean up
delete oldpointer;

// do more with newpointer

// clean up
delete newpointer;

关于C++ 复制指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5959135/

相关文章:

c++ - c++内存分配问题

c++ - glutSolidSphere 没有被点亮

c++ - 错误: "couldn' t infer template argument '_Tp' "when passing in {} into

c++ - 如何使用 g++ 编译 openmp

android - 将自定义类的数组列表转换为 JSONArray

php - 删除关联数组中的键不起作用

C++从基类指针访问派生类成员

c - C中的指针,简单的疑惑

C++ 有没有办法模拟子类和父类之间的 union 行为?

javascript - 如何找到这个数组值的索引号?