【发布时间】:2014-02-09 22:31:22
【问题描述】:
我要做的是:
向卡片组类添加一个函数replace,该函数按值作为参数传递卡片。这 卡片放在牌库的底部
CardPtr 是一个私有类变量,在构造函数中设置为卡组最上面的卡片
node<card> *newCard; //card pointer
newCard = new node<card>(card(2, 0), NULL); //points to the first card
CardPtr = newCard; //sets cardpointer to newcard
一个单独的类取出最上面的卡片并显示值,在此过程中从牌组中删除该节点。我正试图把那张卡放回底部。那么这是代码:
`void deck::replace(card BottomCard)
{
int count = 0;
node<card> *replaceptr;
bottom = NULL;
replaceptr = new node<card>(BottomCard, NULL);
if (bottom != NULL)
{
bottom->next = replaceptr;
}
else
{
bottom = replaceptr;
}
if (count >= 52)
{
throw overflowError("ERROR: Deck is already full");
}
//CardPtr = new node<card>(BottomCard, NULL);
//bottom->next = CardPtr;
}
我在我的主代码中实现了它,它似乎取代了甲板顶部的卡片。任何人都可以帮助我吗?谢谢。
这是我完整的构造函数:
deck::deck() // deck constructor
{
node<card> *newCard; //card pointer
newCard = new node<card>(card(2, 0), NULL); //points to the first card
CardPtr = newCard; //sets cardpointer to newcard
for (int i = 0; i < 4; i++)
{
for (int j = 2; j < 15; j++)
{
if (i == 0 && j == 2) continue;
node<card> *temp = new node<card>(card(j, i), NULL); // temporary pointer sets card value and suit to numbers for value and suit
newCard->next = temp;// sets newcard pointer .next to temp
newCard = temp;// sets newcard to temp
}
}
}
【问题讨论】:
-
请发布一个最小的可编译测试用例。至少包含带有属性的类定义(我想
CardPtr是一个类属性)。 -
您发布的代码还有其他问题。一个明显的错误是您为“底部”分配内存,然后在您的 while 循环中替换“底部”的值。因此,您有内存泄漏。
-
CardPtr的初始值是多少?从给定的代码中并不清楚,这可能对您的逻辑至关重要。
标签: c++ pointers replace linked-list singly-linked-list