【发布时间】:2015-10-26 17:34:33
【问题描述】:
我的课程任务是编写一个程序,该程序创建 52 个卡片对象,每张卡片都有一个价值和一套花色。在我们创建了一个对象数组之后,我们必须随机切换两张牌的位置。问题是当我去交换我的卡时,它们都变成了相同的。这是导致问题的代码:
void SwapCards(Card* cardOne, Card* cardTwo) {
//swap cards here
Card *temp = cardOne;
*cardOne = *cardTwo;
*cardTwo = *temp;
//once it gets here all three variables end up with the same object?
}
现在是调用这个函数的 for 循环:
for (int i = 0; i < 104; i++) {
//get two random values and send them to SwapCards to switch both objects
int c_one = RandomRange(0, 51);
int c_two = RandomRange(0, 51);
SwapCards(deck[c_one], deck[c_two]);
}
对此的任何帮助将不胜感激。我花了很多时间试图弄清楚,但这让我非常困惑。
【问题讨论】:
-
如果你想要引用(和值
temp),请避免使用指针 -
deck的类型是什么? -
@AnonMail 他实际上是在取消引用 cardTwo 并将其分配给取消引用的 cardOne。问题是 temp 不是卡的副本,而是指针。
-
然后查看cplusplus.com/reference/algorithm/swap - 将引用传递给您希望交换的项目而不是指针会更常见。
-
std::swap是核心构建块。不幸的是,许多人从来没有时间教这些东西。