在c++中添加第二个.h/cpp文件时遇到麻烦

trouble with adding second .h/cpp file to C++

本文关键字:文件 cpp 遇到 麻烦 c++ 添加 第二个      更新时间:2023-10-16

我对c++相当陌生,看了看其他几个关于如何包含第二个cpp文件的主题,不确定我到底做错了什么…我主要从网格数组和枚举中得到错误,显然我不能为minimax.h文件使用void ?main.cpp文件的其余部分工作良好,只要我单独编译它

minimax.cpp

#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
void minimax(Grid& grid, Color color_player)
{
    int AI_Play;
    /* initialize random seed: */
    srand (time(NULL));
    /* generate secret number between 0 and grid size: */
    AI_Play = rand() % grid.size() + 0;
    play(grid, AI_Play, color_player)
}

minimax.h

#ifndef MINIMAX_H_INCLUDED
#define MINIMAX_H_INCLUDED
minimax(Grid& grid, Color color_player)
#endif // MINIMAX_H_INCLUDED

main.cpp

#include <SDL.h>
#include <stdio.h>
#include <array>
#include <iostream>
#include <minimax.h>
using namespace std;
//Connect Four Array
#define COLUMN 6
#define ROW 7
//Screen dimension constants
const int SCREEN_WIDTH = 364;
const int SCREEN_HEIGHT = 312;
enum Color {red, black, nothing};
typedef array<array<Color, ROW>, COLUMN> Grid;

您需要将GridColor的声明移动到minimax.h -否则它们将无法在minimax.cpp中看到。您还需要包含minimax.cpp

中的minimax.h

同样,你应该在你的函数中声明返回类型'void'。文件。

尝试更改

#include <minimax.h>

#include "minimax.h"

<header name>为内置标头。

您需要在minimax.h中包含ColorGrid声明,或者将其放在文件的某个地方,然后将其包含在minimax.h中。你的minimax.cpp也应该包括minimax.h

minimax()不知道GridColor是什么,因为您没有在定义minimax()之前定义它们。您的代码应该看起来更像这样:

minimax.h

#ifndef MINIMAX_H_INCLUDED
#define MINIMAX_H_INCLUDED
#include <array>
//Connect Four Array
#define COLUMN 6
#define ROW 7
enum Color {red, black, nothing};
typedef std::array<std::array<Color, ROW>, COLUMN> Grid;
void minimax(Grid& grid, Color color_player);
#endif // MINIMAX_H_INCLUDED

minimax.cpp

#include "minimax.h"
#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
void minimax(Grid& grid, Color color_player)
{
    int AI_Play;
    /* initialize random seed: */
    srand (time(NULL));
    /* generate secret number between 0 and grid size: */
    AI_Play = rand() % grid.size() + 0;
    play(grid, AI_Play, color_player);
}

main.cpp

#include <SDL.h>
#include <stdio.h>
#include <iostream>
#include "minimax.h"
//Screen dimension constants
extern const int SCREEN_WIDTH;
extern const int SCREEN_HEIGHT;
// use minimax() as needed, eg...
int main()
{
    Grid grid;
    ...
    minimax(grid, black);
    ...
    return 0;
}