2016-04-30 7 views
1

Итак, я пытаюсь создать программу, которая имитирует игру «Сапер». Я дважды проверил файлы заголовков, имена классов и убедился, что заголовки # включены в другие файлы cpp, но когда я пытаюсь создать программу, я получаю ошибку LNK2019 в классе «Основной», который у меня есть.C++ LNK2019 ошибка между двумя классами в одном проекте

Ошибка в полном объеме:

Ошибка 1 Ошибка LNK2019: неразрешенный внешний символ "общественности: __thiscall Board :: Board (интермедиат, Int, Int)" (?? 0Board @@ QAE @ HHH @ Z) упоминается в функции _main \ FPSB \ г \ gathmr26 \ Visual Studio 2013 \ Projects \ Сапер \ Сапер \ Main.obj Сапер

я провел, вероятно, около 2 часов, глядя на ответы здесь, на StackOverflow и в других местах и никуда негде. Я пропустил каждую точку в this MSDN page и каждую «общую причину» в this popular answer, и никто из них, похоже, не применим к моей ситуации. Я также пробовал все параметры «Инструменты диагностики» на странице MSDN, и все, что они сделали, просто путают меня больше.

Ближайшее к моей ситуации (насколько я могу судить) this question за исключением того, что весь мой код находится только в одном проекте, а не несколько. Один из тех, кто ответил на этот вопрос, сказал: «Я ввел этот код в свою Visual Studio, и он работал нормально», предположив, что файлы были в одном проекте. Я не понимаю, почему этот ответ заставил его работать там, когда у меня здесь почти такая же ситуация.

Так, во всяком случае, вот код:

main.cpp

#include <iostream> 
#include <string> 
#include "Cell.h" 
#include "Board.h" 

int main() { 
    Board *bee; 
    bee = new Board(50, 50, 50); 

    std::cout << "board created"; 

    return 0; 
} 

Board.cpp

#include <iostream> 
#include <string> 
#include <ctime> 
#include <cstdlib> 
using namespace std; 
#include "Cell.h" 
#include "Board.h" 
#ifndef BOARD_H 
#define BOARD_H 

// Board class. Used to create an array of cell objects to function as data model for Minsweeper game. 
class Board 
{ 
private: 
int width; // number of columns in board 
int height; // number of rows in board 
int mines; // number of mines stored in board 
Cell*** cells; // array storing cell objects 

public: 

// Constructor for board. Takes number of columns, rows, and mines as parameters 
Board::Board(int cols, int rows, int numMines) { 
    width = cols; 
    height = rows; 
    mines = numMines; 
    cells = new Cell**[height]; 
    for (int i = 0; i < height; i++) { 
     cells[i] = new Cell*[width]; 
    } 
    int c = 0; 
    int r = 0; 
    while (r < height) 
    { 
     while (c < width) 
     { 
      setCell(c, r, CellValue::COVERED_CELL); 
      c++; 
     } 
     c = 0; 
     r++; 
    } 
    int m = 0; 
    while (m < numMines) 
    { 
     std::srand(std::time(nullptr)); 
     int x = generateRandomNumberInRange(0, width - 1); 
     int y = generateRandomNumberInRange(0, height - 1); 
     if (!(getCellVal(x, y) == MINE)) 
     { 
      setCell(x, y, CellValue::MINE); 
      m++; 
     } 
    } 
} 

    // Accessor for width field 
int Board::getWidth() 
{ 
    return width; 
} 

// Accessor for height field 
int Board::getHeight() 
{ 
    return height; 
} 

// Accessor for mines field 
int Board::getMines() 
{ 
    return mines; 
} 

// Function to access value of cell located in array where x is column parameter and y is row parameter 
CellValue Board::getCellVal(int x, int y) 
{ 
    CellValue value = CellValue::INVALID_CELL; 

    if (!(x < 0 || x >(width - 1) || y < 0 || y >(height - 1))) 
    { 
     Cell temp = *cells[x][y]; 
     value = temp.getValue(); 
    } 

    return value; 
} 

// Function to set value of cell located in array where x is column parameter and y is row parameter 
void Board::setCell(int x, int y, CellValue value) 
{ 
    if (!(x < 0 || x >(width - 1) || y < 0 || y >(height - 1))) 
    { 
     Cell temp = *cells[x][y]; 
     temp.setValue(value); 
    } 
} 

// Function to determine if game is lost 
// Loops through array to see if there are any UNCOVERED_MINES 
// If so, returns true, game ends, as you've lost :(
// If not, returns false and game can continue 
// Should run after every click action in game 
bool Board::isGameLost() 
{ 
    bool isLost = false; 
    int c = 0; 
    int r = 0; 
    while (r < height) 
    { 
     while (c < width) 
     { 
      if (getCellVal(c, r) == UNCOVERED_MINE) 
      { 
       isLost = true; 
      } 
      c++; 
     } 
     c = 0; 
     r++; 
    } 
    return isLost; 
} 

// Function to determine if game is won 
// Loops through array to determine if there are any falsely flagged mines, unflagged mines, covered cells, or uncovered mines 
// If there are, returns false and game continues 
// If not, returns true, games ends, you've won :) 
bool Board::isGameWon() 
{ 
    bool isWon = true; 
    int c = 0; 
    int r = 0; 
    while (r < height) 
    { 
     while (c < width) 
     { 
      CellValue value = getCellVal(c, r); 
      if ((value == FLAG) || 
       (value == MINE) || 
       (value == COVERED_CELL) || 
       (value == UNCOVERED_MINE)) 
      { 
       isWon = false; 
      } 
      c++; 
     } 
     c = 0; 
     r++; 
    } 
    return isWon; 
} 

}; 


#endif 

Board.h

#include <iostream> 
#include <string> 
#include "Cell.h" 
#ifndef BOARD_H 
#define BOARD_H 

class Cell; 
enum CellValue; 

class Board 
{ 
private: 
    int width; 
    int height; 
    int mines; 
    Cell*** cells; 

public: 
    Board(int cols, int rows, int numMines); 
    int getWidth(); 
    int getHeight(); 
    int getMines(); 
    CellValue* getCellVal(int x, int y); 
    void setCell(int x, int y, CellValue value); 
    void uncoverCell(int x, int y); 
    void flagCell(int x, int y); 
    bool isGameLost(); 
    bool isGameWon(); 
}; 

#endif 

Я знаю, что это распространенная ошибка, которая есть у людей, и что в StackOverflow есть несколько вопросов об этом, но на данный момент я не нашел ни одного, похожего на то, что у меня есть. В чем проблема?

ответ

3

Кажется, что вы смешиваете заголовок и исходные файлы. Ваш файл cpp содержит объявление class со всеми функциями, определенными внутри. Это не похоже на файл cpp. Он должен содержать только объявления функций:

Board::Board(...) 
{ 
    ... 
} 

bool Board::IsGameWon... 

и т.д ...

+0

Лол глупый меня! По-видимому, у меня есть чему поучиться, когда дело доходит до программирования на С ++. Теперь я получил код, и теперь он исправляет ошибки времени выполнения! Спасибо вам за помощь – JaykeBird