簡體   English   中英

C ++復制指針

[英]C++ Copying Pointers

嗨,我想知道如何將C ++中的2d數組指針的內容復制到另一個位置並設置另一個指針,這樣當我對復制的指針進行更改時,原始數據沒有任何反應?

基本上它是指向棋盤上棋子的數組指針。 所以它就像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,你甚至應該能夠使用默認的復制構造函數。

您可以通過在目標分配內存然后進行memcopy來進行復制

dest_pointer = (<<my type>>*) malloc(sizeof(<<my type>>);
memcpy(dest_pointer, src_pointer, sizeof(<<my type>>);

順便說一句,這些方法永遠不會被復制。 它們不屬於某個對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM