C++简单的类程序无法编译。我搞砸了包含标题吗? 'Error redefinition of a class'

C++ Simple class program wont compile. Did i mess up the include headers? 'Error redefinition of a class'

本文关键字:标题 Error class of redefinition 包含 程序 简单 编译 C++      更新时间:2023-10-16

我只有一个简单的程序,其中dice.cpp和dice.h通过game.cpp运行,到目前为止,只计算两次掷骰子的总和。

当我试图运行程序时,显然我正在重新定义Dice类,这就是我的错误告诉我的

这是我的三份文件。

game.cpp

#include "Dice.h"
#include <iostream>
using namespace std;
int main()
{ int sum;
  Dice dice1;
  Dice dice2;
  dice1.roll();
  dice2.roll();
  sum = dice1.getFace() + dice2.getFace();
  cout << sum;
  return 0;
}

骰子.cpp

#ifndef DICE_H
#define DICE_H
#include "Dice.h"
using namespace std;
// g++ -c Dice.cpp
// default constructor: initializes the face of a new
// Dice object to 1
Dice::Dice()
{
  //cout <<  "Default constructor " << endl;
  face = 1; // not redeclaring the data member face
}

// specific constructor: initializes the face of a new
// Dice object to newFace
// Pre-condition: newFace is a valid number
// call setFace function inside Dice(int newFace)
Dice::Dice(int newFace)
{
    //cout << "Specific constructor " << endl;
    setFace(newFace);
}

// Sets face to the value in otherFace
// Pre-condition: otherFace is valid
void Dice::setFace(int otherFace)
{
    assert(otherFace >= 1 && otherFace <= 6);
    face = otherFace;
}

// Changes the value of face to a random value between 1 and 6
void Dice::roll()
{
  face = rand()%6 +1;
}
// returns the face value of a Dice object
int Dice::getFace() const
{
    return face;
}
    // displays the face value of a Dice object
void Dice::display() const
{
     cout << "This dice has " << face << " on top" << endl;
}
#endif

骰子

#include <iostream>
#include <cassert>
#include <cstdlib>
#include <ctime>
// definition of class Dice
class Dice
{
  private:
    int face; // can only take values between 1 and 6
  public:
    // default constructor: initializes the face of a new
    // Dice object to 1
    Dice();
  // specific constructor: initializes the face of a new
    // Dice object to newFace
    // Pre-condition: newFace is a valid number
    // call setFace function inside Dice(int newFace)
    Dice(int newFace);
    // Sets face to the value in otherFace
    // Pre-condition: otherFace is valid
    void setFace(int otherFace);
    // Changes the value of face to a random value between 1 and 6
    void roll();
    // returns the face value of a Dice object
    int getFace() const;
    // displays the face value of a Dice object
    void display() const;
};

这是错误的照片

在"dice.cpp"文件中,删除第三行"#include"dice.h。您已经定义了dice类,因此不需要#include语句

您显示的代码是骗人的。错误似乎是说game.cpp包括Dice.h,而Dice.h包括Dice.cpp,后者包括Dice.h。因此,您的Dice.h头文件被包含两次,如果头文件中没有头包含保护,则类将被定义两次。

简单的解决方案?不要包含文件。不过,在头文件中仍然应该有头包含保护。

相关文章: