简体   繁体   English

让一个 .cpp 文件与一个 class.cpp 和一个 class.h 文件通信

[英]Having one .cpp file communicate with a class.cpp and a class.h file

I don't know the correct syntax for Dice.h and Dice.cpp to talk to my final game.cpp file.我不知道 Dice.h 和 Dice.cpp 与我的最终 game.cpp 文件对话的正确语法。

I am getting a compile error that is returning a undefined reference to Dice::Dice()我收到一个编译错误,返回对 Dice::Dice() 的未定义引用

Here are my 3 file headers这是我的 3 个文件头

Game.cpp游戏.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;

}

Dice.h骰子

#include <iostream>
#include <cassert>
#include <cstdlib>
#include <ctime>


// definition of class Dice
class Dice //... cont

Dice.cpp骰子.cpp

#include "Dice.h"
using namespace std;


Dice::Dice() //... cont 

I get the error when i compile by typing g++ -Wall -o game game.cpp Is this the correct way to compile multiple files?当我通过键入 g++ -Wall -o game game.cpp 进行编译时出现错误 这是编译多个文件的正确方法吗?

Just because you have the includes in the files doesn't mean they will be compiled together.仅仅因为文件中有包含并不意味着它们会被编译在一起。

Try g++ -Wall -o game Dice.cpp Game.cpp试试 g++ -Wall -o game Dice.cpp Game.cpp

...I could be slightly wrong on the command but that should work ...我在命令上可能有点错误,但这应该有效

Side note you should really look into Makefiles.旁注,您应该真正研究一下 Makefile。 Makes everything so much easier.让一切变得如此简单。

The other answer is close, but slightly off.另一个答案很接近,但略有不同。 Enter进入

++ -Wall -o game game.cpp Dice.cpp

Make sure that game is lower case, and I think the file containing main() needs to go first.确保游戏是小写的,我认为包含main()的文件需要先行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM