-1

我需要使用 Dice 类编写掷骰子的 C 程序。主要要求是我需要使用这个main,编辑它:

int main()
{
      Dice* ptrDice;
             ???
      for (int i = 0; i < 5; i++)
      {
           ????                // roll the 5 dice
           ????                // print the outcome
      }
}

我只是无法在这里获得如何使用指针。任何人都可以帮忙吗?

这是我的代码,但它不起作用:(

#include <iostream>
#include <iomanip>
#include <cstdlib>

using namespace std;

class Dice{
  public:
    Dice();
    int getNums();
    void Roll();
  private:
    int nNums;
};

Dice::Dice(){
    nNums=5;
}
int Dice::getNums()
{
    return nNums;
}
void Dice::Roll()
{
    nNums = rand()%6 + 1;
}

int main()
{
      Dice* ptrDice = new Dice;
      ptrDice -> getNums();
      for (int i = 0; i < 5; i++)
      {
       getNums[i] = rand()%6 + 1;                // roll the 5 dice
       cout << "You rolled: ";
       cout << ptrDice->getNums() << setw(4);
       cout << endl;                             // print the outcome
      }
}

我猜我的主要麻烦是使用那个 ptrDice 并在 main 函数中打印它!

4

1 回答 1

1

你让这变得比它需要的更复杂。

一个简单的 Dice 对象不需要数据成员,只需要一个成员函数。如果您使用的是 rand() 函数,则构造函数应使用 srand(seed) 为随机数生成器播种。Roll() 函数应将滚动的数字返回为 int。您根本不需要 getNums() 函数,它只会在定义您的类时返回 5。

class Dice() {
public:
    int roll() { return rand() % 6 + 1; }
};

...

int main() {
    Dice* ptrDice = new Dice;
    for (int i=0; i<5; i++) {
        cout << "You rolled" << ptrDice->roll() << '\n';
    }
    delete ptrDice;
}

您可以扩展此类以模拟具有任意数量面的多个骰子。然后你可以使用整数数据成员来保留骰子的数量和它们的边数。

于 2013-11-13T04:33:52.353 回答