对 c++ 有点陌生,并收到错误消息"error: a function-definition is not allowed here before '{' token"



目前正在为我的c++类创建一个战列舰游戏,我正在努力创建一种可以将每艘船随机放置在棋盘上的方式。到目前为止,我已经想出了这个问题,唯一的问题是我的船相互重叠。为了解决这个问题,我在while循环中设置了另一个条件,该条件调用一个函数来检查是否占用了该点。我以为这一切都会很好,但我收到了这个错误消息,现在我几乎陷入了困境。

#include "ship.h"
#include "board.h"
#include <ctime>
#include <iostream>
using namespace std;
void Ship::setShip(Board &board) {

bool isOpen(int x, int y);
srand(time(0) * (size+rand()));
int x = rand() % 10;
int y = rand() % 10;
int orientation = rand() % 2 == 0 ? 0 : 1;
string open = "[ ]";
if (orientation == 0) {
// check if ship is off the board 
while (x + size > board.COLS || !isOpen(x, y)) {
x = rand() % 10;
y = rand() % 10;
}
for (int i = x; i < x + size; i++) {
board.board[i][y] = shipLetter;
}
} else {
while (y + size > board.ROWS || board.board[x][y] != open) {
x = rand() % 10;
y = rand() % 10;
}
for (int i = y; i < y + size; i++) {
board.board[x][i] = shipLetter;
}
}

bool isOpen(int x, int y)
{
bool taken = false;
for (int i = 0; i < size; i++) {
if (board.board[x + i][y] != open) {
taken = true;
}  else {
taken = false;
}
}
return taken;
}
}

对于未来,请阅读并考虑https://stackoverflow.com/help/how-to-ask

这一点非常重要,因为如果不提出一个好问题,你就无法得到一个好的答案。

无论如何,我都会尝试,因为有一点在您的代码中是显而易见的。

将函数定义isOpen移到setShip的方法体之外,并移到它之前。所以根据这个:

...
bool isOpen(int x, int y) { 
.... full function implementation here
}
void Ship::setShip(Board& board) { 
// isOpen(int x, int y); <-- remove this line
.... rest of method implementation here
}

这将至少解决您在此处报告的错误。但是,如果代码无论如何都能工作,或者能立即实现您的期望,我会感到惊讶。。。但这是一个不同的问题。

不能在另一个函数中定义一个函数。

最新更新