我第一次在C ++中使用自己的自定义头文件。该程序的目标是创建一个骰子类,该类可用于创建面向对象的骰子游戏。
当我运行程序(由三个文件(标头/类规范文件,类实现文件,最后是应用程序文件)组成时,出现错误:
对`Die :: Die(int)'的未定义引用
在运行app.cpp
时,我大约有六个错误,每次尝试访问Die
类中的信息时都会出现一个错误。
#ifndef DIE_H
#define DIE_H
#include <ctime>
//#include
class Die
{
private:
int numberOfSides=0;
int value=0;
public:
Die(int=6);
void setSide(int);
void roll();
int getSides();
int getValue();
};
#endif
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Die.h"
using namespace std;
Die::Die(int numSides)
{
// Get the system time.
unsigned seed = time(0);
// Seed the random number generator.
srand(seed);
// Set the number of sides.
numberOfSides = numSides;
// Perform an initial roll.
roll();
}
void Die::setSide(int side=6){
if (side > 0){
numberOfSides = side;
}
else{
cout << "Invalid amount of sides\n";
exit(EXIT_FAILURE);
}
}
void Die::roll(){
const int MIN_VALUE = 1; // Minimum die value
value = (rand() % (numberOfSides - MIN_VALUE + 1)) + MIN_VALUE;
}
int Die::getSides()
{
return numberOfSides;
}
int Die::getValue()
{
return value;
}
#include <iostream>
#include "Die.h"
using namespace std;
bool getChoice();
void playGame(Die,Die,int &, int &);
int main()
{
int playerTotal=0;
int compTotal=0;
Die player(6);
Die computer(6);
while(getChoice()){
playGame(player, computer, playerTotal, compTotal);
getChoice();
}
}
void playGame(Die play, Die comp, int &pTotal, int &cTotal){
//add points
play.roll();
pTotal += play.getValue();
comp.roll();
cTotal += comp.getValue();
//show points each round
cout << "You have " << pTotal << " points;\n";
}
bool getChoice(){
bool choice;
cout << "Would you like to roll the dice? (Y/N): ";
cin>> choice;
return choice;
}
答案 0 :(得分:0)
您应该同时编译app.cpp
和Die.cpp
:
g++ app.cpp Die.cpp