我试图教自己C++,所以我正在做一个战舰程序。我有一个船舱和木板舱。
这个版本相当标准。玩家进入一个细胞的坐标试图击中一艘船。说明船只是否被击中的程序。如果一艘船占用的所有单元格都被击中,程序将打印一条消息,说明该船已沉没。每次尝试之后,程序通过显示板,并分别用"*"或"x"标记所有成功的尝试来打印当前状态。
我在我的Board类中实现Ship *shipAt(int x, int y)函数时遇到了困难,因为它本质上是一个返回指向该船的指针的函数。否则,它返回一个空指针。
我为战列舰准备了一个板
a b c d e f g h i j
+-------------------+
0| |
1| |
2| |
3| |
4| |
5| |
6| |
7| |
8| |
9| |
+-------------------+下面是我的ship类中的bool Ship::includes(int x, int y)函数,我试图实现这个函数来完成我的shipAt函数。我把它剪下来是为了简洁:
#include "Ship.h"
#include <iostream>
#include <stdexcept>
using namespace std;
//Would have been more member functions but I cut it down for brevity
bool Ship::includes(int x, int y)
{
bool include= false;
if(x == x1)
{
if ((y>= y1) && (y<=y2))
{
include = true;
}
if ((y>= y2) && (y<=y1))
{
include = true;
}
}
else if (y == y1)
{
if ((x>= x1) && (x<=x2))
{
include = true;
}
if ((x>= x2) && (x<=x1))
{
include = true;
}
}
return include;
}
},这是我的董事会班。如果船舶占用单元格(x,y),则该函数返回指向该船的指针,则该函数的Ship *shipAt(int x, int y) 函数在此函数中出现问题。否则,它将返回一个空指针.
#include "Board.h"
#include "Ship.h"
#include <iostream>
using namespace std;
#include <vector>
#include <string.h>
#include <stdexcept>
//member function definitions
Board::Board(void)
{
char score[10][10] = {};
}
void Board::addShip(char type, int x1, int y1, int x2, int y2)
{
if(shipList.size()<10)
{
shipList.push_back(Ship::makeShip(type,x1,y1,x2,y2));
}
}
void Board::print(void){
cout<< " a b c d e f g h i j"<< endl;
cout <<" +-------------------+"<< endl;
for (int i = 0; i < 10; i++) {
// print the first character as part of the opener.
cout << " " << i << "|" << score[i][0];
for (int j = 1; j < 10; j++) {
// only add spaces for subsequent characters.
cout << " " << score[i][j];
}
cout << " |" << endl;
}
cout <<" +-------------------+"<< endl;
}
void Board::hit(char c, int i){
if (c<'a' || c>'j' || i > 9 || i<0){
throw invalid_argument("invalid input");
}
Ship* ship = shipAt(i, c-'a');
if (ship) {
score[i][c-'a']= '*';
}
else{
score[i][c-'a']= 'x';
}
}
Ship* Board::shipAt(int x, int y){
Ship* ship = Ship::includes(x,y);
if (ship){
return ship;
}
else{
return NULL;
}
}
int Board::level(void)
{
int lev = 0;
std::vector<Ship *>::iterator iter = shipList.begin();
std::vector<Ship *>::iterator end = shipList.end();
for ( ; iter != end; ++iter )
{
lev += (*iter)->level();
}
return lev;
}实际上,我试图使用Ship类中的bool Ship::includes(int x, int y)函数。我试图这样做,以便如果函数返回为true,那么atShip函数也将返回true,因为包含函数是布尔函数。
但是,该实现不起作用,而且我正在接收对非静态成员函数的调用,而没有对象参数错误。
编辑:用于其他上下文的(可能没有必要,所以除非您需要,否则不要单击),
这是我的Ship.cpp:http://pastebin.com/cYDt0f8W
以下是我的Ship头文件:http://pastebin.com/W6vwKJRz
以下是我的董事会头文件:http://pastebin.com/r36YjHjt
发布于 2014-05-26 23:39:51
Ship* ship = Ship::includes(x,y);
Ship::includes()返回一个bool而不是一个Ship*Ship::includes()不是static您需要查看您的船只列表,每次测试它都是"at“(x,y)。一旦你找到一艘船,你就可以归还它。
类似于(伪代码):
foreach ship in shipList
if (ship->includes(x, y))
return ship
return NULL;https://stackoverflow.com/questions/23879003
复制相似问题