我是一名c ++初学者,我需要创建一个模拟滚动两个骰子的骰子游戏。我对使用头文件很困惑。但首先,为什么我需要返回骰子的脸部?第二,int roll功能有什么作用?要重置值和面?如果是这样,默认值是多少?最后一个函数Dice(int n),我是否使用这个函数来控制骰子值的最大值?该函数必须具有包含以下函数的类头文件:
class Dice{
private:
int face; // no. of faces of the dice
int value; // the face-value that shows up
public:
int getFace()// returns the no. of face of the dice
{
};
int getVal()
{
int dice1;
int dice2;
dice1 = rand() % 6 + 1;
dice2 = rand() % 6 + 1;
}; // returns the face value that shows up
int roll(); // simulate the roll pf the dice, the value field is set and returned.
Dice(); // default constructor , a standard six-face dice is created with value = 1
Dice(int size); // create a dice of given size
};
答案 0 :(得分:2)
希望这能按顺序回答您的问题:
我能看到返回每个骰子的面数的唯一原因是告知用户当前正在掷骰子。我在下面的代码中展示了这个例子,我有dOne.getFaces()和dTwo.getFaces()。
int roll()函数和getVal()应该和我假设的一样。我已经继续并删除了getVal()而只是使用了roll()。
Dice()和Dice(int size)只是初始化每个骰子的面数。默认骰子将有6个面,但是用户可以掷出超过6的骰子,因此是int大小。
#include <iostream>
#include <cstdlib>
#include <time.h>
class Dice
{
private:
int faces; // no. of faces of the dice
int value; // the face-value that shows up
public:
int getFaces() {return faces;} // returns the no. of faces of the dice
int roll() // returns the face value that shows up
{
value = rand() % faces + 1;
return value;
}
Dice() : faces(6) {}; // default constructor, create a dice of standard size
Dice(int size) : faces(size) {}; // create a dice of given size
};
int main()
{
srand( time(NULL) ); // Initialize random seed
char yesNo;
std::cout << "\nWould you like to roll two normal dice? (y/n)\n";
std::cin >> yesNo;
if ( yesNo == 'y' )
{
Dice dOne, dTwo;
std::cout << "\nA dice with " << dOne.getFaces() << " faces rolled: " << dOne.roll() << '\n';
std::cout << "A dice with " << dTwo.getFaces() << " faces rolled: " << dTwo.roll() << '\n';
}
else
{
int dFaces;
std::cout << "\nHow many faces would you like each dice to have?\n\n";
std::cout << "Dice 1: ";
std::cin >> dFaces;
Dice dOne(dFaces);
std::cout << "Dice 2: ";
std::cin >> dFaces;
Dice dTwo(dFaces);
std::cout << "\nA dice with " << dOne.getFaces() << " faces rolled: " << dOne.roll() << '\n';
std::cout << "A dice with " << dTwo.getFaces() << " faces rolled: " << dTwo.roll() << '\n';
}
return 0;
}
答案 1 :(得分:0)
您需要定义构造函数。构造函数的作用是设置类的状态,所以在这种情况下它会设置有关骰子的信息。
如果要将它们直接放在标题中,那么构造函数的格式如下所示:
//file: dice.h
//this is default constructor, note the lack of parameters being passed in
Dice(): face(?), value(?) // here we are initializing "face" and "value", replace the question marks with the correct values as per your specification
{
}
如果你在cpp文件中这样做,它有点不同但逻辑应该保持不变。
//file: dice.h
Dice(); //This is only a declaration
//file: dice.cpp
#include "dice.h"
Dice::Dice(): face(?), value(?) //This is where we define the constructor. note the Dice:: part here, we need to tell the compiler where to look
{
}
其余部分非常相似。如果你正在努力,那么我建议你进一步研究一些c ++资源。我会查找构造函数/析构函数以及初始化列表。