我假設你想要將實體的實例從sendingSquare移動到receivingSquare,並調整移動的實體的currentSq,使其返回到receivingSquare。
,如果是這樣的話,下面的代碼將做到這一點:
#include <iostream>
using namespace std;
class Square;
class Entity
{
public:
Square *currentSq;
Entity(): currentSq(NULL){}//set currentSq to NULL using constructor initialization list
};
class Square
{
public:
Entity *occupant;
Square(): occupant(NULL){}//set occupant to NULL using constructor initialization list
};
//MOVE_TO with single '*'
void MOVE_TO(Square *sendingSquare, Square *receivingSquare)
{
Entity *movingOccupant = sendingSquare->occupant;
receivingSquare->occupant = movingOccupant;
movingOccupant->currentSq = receivingSquare;
sendingSquare->occupant = NULL;
}
int main(int argc, char** argv) {
//create instances
Square *sendingSquare = new Square(), *receivingSquare = new Square();
Entity *entity = new Entity();
//set up instances accordingly
sendingSquare->occupant = entity;
entity->currentSq = sendingSquare;
//print instances address before MOVE_TO invoked
//we know that receivingSquare.occupant is NULL, printing receivingSquare.occpuant.currentSq is commented
cout << "sendingSquare: "<< sendingSquare
<< ", sendingSquare.occupant: " << sendingSquare->occupant
<< ", sendingSquare.occupant.currentSq: " << sendingSquare->occupant->currentSq
<< ", receivingSquare: " <<receivingSquare
<< ", receivingSquare.occupant: " << receivingSquare->occupant
//<< ", sendingSquare.occupant.currentSq: " << receivingSquare.occupant->currentSq
<< endl;
MOVE_TO(sendingSquare,receivingSquare);
//print instances address afer MOVE_TO invoked
//we know that sendingSquare.occupant is NULL, printing sendingSquare.occpuant.currentSq is commented
cout << "sendingSquare: "<< sendingSquare
<< ", sendingSquare.occupant: " << sendingSquare->occupant
//<< ", sendingSquare.occupant.currentSq: " << sendingSquare.occupant->currentSq
<< ", receivingSquare: " << receivingSquare
<< ", receivingSquare.occupant: " << receivingSquare->occupant
<< ", receivingSquare.occupant.currentSq: " << receivingSquare->occupant->currentSq
<< endl;
//commenting instance deletion. The program is ended anyway
//delete entity,sendingSquare,receivingSquare;
return 0;
}
爲什麼你使用'廣場**'指針而不是簡單的'廣場*'指針作爲'MOVE_TO'參數這是完全不清楚,但如果正確完成,那仍然可以工作。它應該以目前的形式運作。我在MOVE_TO裏面看不到任何會產生你描述的奇怪行爲的東西。無論如何,呼叫MOVE_TO的地方在哪裏?你怎麼稱呼它? – AnT
我會改變'MOVE_TO'上的套管。它看起來像一個宏,因爲宏通常都是大寫的,所以它們以宏的形式出現。 – chris
@AndreyT我會嘗試使用單指針,看看有什麼。 – Ian