C++复制指针
C++ Copying Pointers
嗨,我想知道如何将 2d Array C++指针的内容复制到另一个位置,并将另一个指针设置为它,以便在我对复制的指针进行更改时,原始数据不会发生任何变化?
基本上它是一个指向棋盘上棋子的数组指针。 所以它就像Piece * oldpointer = board[8][8]
. 现在我想将此指针中的所有内容(包括 Pieces 头文件中的 getvalue(), getcolor()
等方法)复制到另一个位置,并设置指向它的指针,以便我可以在那里进行操作并测试它,而不必影响此原始数据?我在我不得不使用的地方读到allocate()
但我不确定。请帮忙
在C++中,您可以按如下方式定义 2D 数组类型(您需要现代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++,为什么不为你的 Piece 类定义一个复制构造函数呢?然后只是
Piece copied_piece(*board[8][8]);
如果你的类是 POD,你甚至应该能够使用默认的复制构造函数。
您可以通过在目标位置分配内存然后进行内存复制来复制
dest_pointer = (<<my type>>*) malloc(sizeof(<<my type>>);
memcpy(dest_pointer, src_pointer, sizeof(<<my type>>);
顺便说一句,这些方法永远不会被复制。 它们不属于对象。
相关文章:
- C++指针复制重载
- 将值从指针复制到常量对象参数
- 在 C++ 中通过字符串指针复制字符串变量中的字符串
- 使用指针复制构造函数用法
- 将对象的指针复制到此对象的新指针中
- 如何将指向 int(数组)的指针复制到 int 数组?
- 从指针复制对象
- C 使用指针复制char*
- 使用随机指针C 复制列表
- 如何在C++中从void指针复制数据
- 在 C++ 中将一个指针复制到另一个指针
- 正在将指针复制到assign运算符中的另一个列表元素
- 从压缩的DIB无效指针复制
- 无法从字符指针复制到短
- C++使用指针复制构造函数
- 将对象指针复制到动态对象数组中
- 在 CUDA 中使用指针复制类
- 从指针复制派生对象
- 如何使用智能指针复制C++更改指针
- 将内容从一个指针复制到另一个指针