使用自定义头文件时出现 C++ "undefined reference" 错误

C++ "undefined reference" error when working with custom header file

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

当我转到 运行 我的程序(由三个文件组成(header/class 规范文件,class 实现文件,最后是应用程序文件)时,我收到一个错误:

undefined reference to `Die::Die(int)'

我在 运行ning app.cpp 时遇到了大约六个这样的错误,每次我尝试从 Die class.[=18 访问信息时都会遇到一个错误=]

完整的错误信息

我的三个文件

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

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

g++ app.cpp Die.cpp