gpt4 book ai didi

c++ - C++ 中的简单类概念(一副牌)

转载 作者:行者123 更新时间:2023-11-28 01:10:12 27 4
gpt4 key购买 nike

类(class)让我很困惑!对于这个特定的任务,我们将执行经典的“卡片组中的卡片”程序。我们要创建两个类,一个称为“Card”,另一个称为“Deck”。到目前为止,我已经完成了其中的大部分工作,但我似乎忘记了一个概念。

当我们调用 Card 类的默认构造函数时,将创建所有 52 张卡片,以便 Deck 类可以使用这些对象并......创建一副牌!现在我参加了与我们的助教的 session ,他强调默认构造函数是初始化值,而 Deck 类获取这些对象并循环遍历它们以使用将真实卡片值分配给 Card 对象的函数。

我的问题是:创建这些对象以便 Deck 可以引用它们的最佳方法是什么?我现在的想法是创建一个名为“initialCard[4][13]”的固定数组。从那里,Deck 类将选择一个值——比如“initialCard[0][0]”,并将其分配给仅来自二维数组的行和列的黑桃 A。但是,我的助教一直在说“创建一个 Card 对象数组”。他这话是什么意思?我有一点把握,但我只是不确定......有人有什么想法吗?谢谢!

也许这会有所帮助;直接从作业页面:

Your card class should have public getter and setter functions for both of these variables (getValue, setValue, etc), as well as a function that will return a c-string representation of the card. (You can call it toCString if you want.) It should work something as follows:

void toCString(char cardString[]) INPUT: A character array for storing the output OUTPUT: NONE This function should return a character string representing the card object. This string must have the following form: two characters followed by a third null byte. The first character represents suit; the second represents value. Suits should be “S”, “H”, “C”, or “D” for spades, hearts,

clubs, diamonds. The second character represents value: “A” for Ace, 2-9 for numbered cards, “T” for 10, “J” for Jack, “Q” for Queen”, “K” for King. Some examples: 2 of spades = 'S2' 10 of hearts = 'HT' Jack of diamonds = 'DJ' Queen of clubs = 'CQ' Ace of spades = 'SA' etc.

In addition to these, you should have at least a default constructor to initialize the values. You are welcome to create other constructors (perhaps one that initializes a card from it's c-string representation?) but it is not required.

Deck Class: In addition to your card class, you will need to create a Deck class to encapsulate all of your card objects. In this object you should have a private member multi-dimensional array (of size SUITS by VALUES) of your Card objects. When a Deck object is created, you should have it initialize the multi- dimensional array of Cards. Card suits are represented by an enumerated type; card values are represented by an integer from 1 to 13 (1 is an Ace, 2-10 are numbered values, 11 is the Jack, 12 is the Queen, and 13 is the King).

Your constructor should loop over the multi-dimensional array and initialize all values so that the complete deck of cards is represented.

最佳答案

听起来您没有得到最好的建议。

将对象构造成真正有效的状态总是更清晰。因此,与其使用无意义的值默认构建卡片然后再填充,不如使用正确的值构建它们。这可以使用 vector 来完成,它具有数组的大部分优点。

所以,你会有

class deck {
std::vector< Card > cards;
...
deck() {
// no cards yet at this point
for ( size_t i = 0; i < 52; ++ i ) {
cards.push_back( Card( i ) );
}
// now array is valid
...

避免使用具有非平凡构造函数的 C 风格类数组。

关于c++ - C++ 中的简单类概念(一副牌),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3827320/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com