使用自定义头文件时出现C ++“未定义引用”错误

时间:2020-07-28 02:14:08

标签: c++ amazon-web-services object debugging header-files

我第一次在C ++中使用自己的自定义头文件。该程序的目标是创建一个骰子类,该类可用于创建面向对象的骰子游戏。

当我运行程序(由三个文件(标头/类规范文件,类实现文件,最后是应用程序文件)组成时,出现错误:

对`Die :: Die(int)'的未定义引用

在运行app.cpp时,我大约有六个错误,每次尝试访问Die类中的信息时都会出现一个错误。

完整错误消息

error message image

我的三个文件

Die.h

#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 

Die.cpp

#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;
}

app.cpp

#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;
}

1 个答案:

答案 0 :(得分:0)

您应该同时编译app.cppDie.cpp

g++ app.cpp Die.cpp