您好,我想知道如何将 C++ 中的二维数组指针的内容复制到另一个位置并设置另一个指向它的指针,以便当我对复制的指针进行更改时原始数据不会发生任何变化?
基本上它是一个指向棋盘上棋子的数组指针。所以它就像Piece * oldpointer = board[8][8]
。现在我想复制这个指针中的所有内容,包括 Pieces 头文件中的 getvalue()、getcolor() 等方法到另一个位置,并设置一个指向它的指针,以便我可以执行操作在那里进行测试而不影响原始数据?我在某处读到我必须使用 allocate()
但我不确定。请帮忙
Hi i would like to know how i could copy the contents of a 2d Array pointer in C++ to another location and set another pointer to it so that when i make changes on the copied pointer nothing happens to the original data?
Basically its an array pointer to pieces on a chessboard. so it goes like Piece * oldpointer = board[8][8]
. now i want to copy all the contents in this pointer including methods like getvalue(), getcolor()
etc which are in the Pieces header file to another location and set a pointer to it so i can do operations there and test it without it having to affect this orginal data? I read somewhere i had to use allocate()
but im not sure. please help
发布评论
评论(3)
在 C++ 中,您可以按如下方式定义 2D 数组类型(您需要现代 C++ 编译器):
如果您的编译器不支持
std::array
,您可以使用boost::array
代替:现在您可以使用上面的类型。正如我所看到的,您需要复制指针指向的对象:
In C++ you could define 2D array type as follows (you need modern C++ compiler):
If your compiler doesn't support
std::array
you can useboost::array
instead:Now you can use the type above. As I can see you need to copy the object to which the pointer points:
既然您使用的是 C++,为什么不为 Piece 类定义一个复制构造函数呢?那么
如果你的类是 POD,你甚至应该能够使用默认的复制构造函数。
Since you're using C++, why not define a copy constructor for your Piece class? Then just
If your class is POD, you should even be able to get by with the default copy constructor.
您可以通过在目标分配内存然后 memcopy 来进行复制
顺便说一句,这些方法永远不会被复制。它们不属于某个对象。
You can copy by allocating memory at the destination and then memcopy
Btw, the methods are never copied. they don't belong to an object.