这是一款基于控制台的迷宫游戏。我们的想法是在头文件中编写游戏类,并在主线程中使用该类。我不确定我做得对,因为我收到了错误。我如何在代码中包含头文件?
我正在使用Cloud9,所以我不知道Cloud9和应用软件IDE之间是否存在差异。我是C ++的新手,只使用了几个星期(3-4),所以我想知道我做的是不是正确。
以下是我的代码的结构:
这是 MazeGame.h:
#ifndef MAZEGAME_H
#define MAZEGAME_H
class Maze{
protected:
int width;
int height;
std::string maze;
public:
Maze(int width, int height){
this->width = width;
this->height = height;
}
static void setMazeBlock(std::string value){
this->maze += value;
}
void destroyMazeBlock(int set){
this->maze[set] -= this->maze[set];
}
std::string getMazeDrawing(){
return this->maze;
}
void setMazeDrawing(std::string val){
this->maze = val;
}
void drawMaze(int times = 1){
for(int i = 0; i <= times; ++i){
std::cout << this->maze;
}
}
void generate(){
for(int i = 0; i < this->width; ++i){
this->setMazeBlock("#");
}
this->setMazeBlock(std::endl);
for(int i = 0; i < this->width; ++i){
this->setMazeBlock("#");
for(int j = 0; j < this->height; ++j){
this->setMazeBlock(std::endl);
if(j == this->width){
this->setMazeBlock("#");
}
}
}
for(int i = 0; i < this->width; ++i){
this->setMazeBlock("#");
}
this->setMazeBlock(std::endl);
}
};
这是 MazeGame.cpp :
#include <iostream>
#include <MazeGame.h>
int main(){
Maze m = new Maze(16, 16);
return 0;
}
两个文件都在同一目录中。但是,我在控制台上收到此错误:
/home/ubuntu/workspace/Maze/MazeGame.cpp:4:22: fatal error: MazeGame.h: No such file or directory
#include <MazeGame.h>
^
答案 0 :(得分:3)
由于您的标头文件是用户定义的,您应该用双引号声明它:
#include "MazeGame.h"
您尝试声明它的方式是您将用于内置标头的方法。例如:
#include <iostream>
答案 1 :(得分:2)
包含应该是:
#include <iostream> // <...> for standard headers
#include "MazeGame.h" // "..." for your own headers
错误来自于使用<...>
作为您自己的标头,这会导致编译器在错误的位置查找您的标头。
您还可以考虑在cpp文件中移动成员函数定义,只在标题中留下其签名声明:
标题文件:
class Maze{
protected:
...
public:
Maze(int width, int height);
static void setMazeBlock(std::string value);
...
};
cpp文件:
Maze::Maze(int width, int height){
this->width = width;
this->height = height;
}
void Maze::destroyMazeBlock(int set){
maze[set] -= maze[set]; // n need for this-> here
}
...
顺便说一下,制作headers self sufficient是一个很好的做法,所以要在标题中包含他们所依赖的其他标题,而不要期望你在cpp中这样做(所以由于std: :string,建议在标题中包含<string>
。
答案 2 :(得分:1)
致命错误:MazeGame.h:没有此类文件或目录
#include <MazeGame.h>
编译器无法在搜索路径中找到MazeGame.h
文件。
#include "MazeGame.h"
和#include <MazeGame.h>
之间的差异是编译器搜索头文件的位置。 Cloud9使用GCC编译器,它以这种方式指定include syntax:
将目录添加到此列表中
#include <file>
它在标准的系统目录列表中搜索名为file
的文件。您可以使用-I选项将目录添加到引用目录列表中
#include "file"
它首先在包含当前文件的目录中搜索名为file
的文件,然后在引用目录中搜索,然后搜索用于<file>
的相同目录。您可以使用-iquote选项
因此,对于用户定义的标头,您应该使用"file"
并在上面的代码中使用#include "MazeGame.h"
。
答案 3 :(得分:0)
编写#include <>
不是必需的,但默认情况下是内置的,但仅适用于您的编译器包含目录。
所以如果你想用这种方式写作然后工作:
添加新头文件的文件夹以包含编译器,然后您可以编写:
#include<MazeGame.h>
或者您可以将此头文件复制到包含文件夹,它将正常工作。安装像openGL这样的新库时,我们将标题复制到include folder
和lib
文件到lib文件夹。
默认情况下使用include ""
告诉编译器该文件位于当前工作目录中。
#include <iostream>
所以在这种情况下编译器会在当前目录中搜索iostream,如果找不到它,它会在编译器的所有包含文件夹中搜索它(内置和添加的目录) )